﻿/* ====================================================================
   Licensed to ...
==================================================================== */

/* ================================================================
 * Author: Salvatore Garrubba
 * Author's email: salvatore.garrubba (at) outlook (dot) com
 * HomePage: http://www.softwarepescaspinning.com/
 * Contributors:
 * 
 * ==============================================================*/

#define FAST_TEST
#undef  FAST_TEST
#define VERBOSE_MODE
#undef VERBOSE_MODE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
using System.Collections.ObjectModel;
using System.Net;
using System.IO;
using System.Threading;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Globalization;
using System.Data;
using NPOI.HSSF.UserModel;
using System.Windows.Threading;
using System.Collections.Concurrent;
using System.Xml;
using Microsoft.Win32;
using System.Data.SqlClient;

namespace FishingSearch
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
            StackPanelLeftMenu.DataContext = new ExpanderListViewModel();

#if !DEBUG 
            //check validation of the installation, only in release mode
            if (!IsInstallationValid())
            {
                ApplicationNotValid();
                this.Close();
            }
#endif

        }


        #region field

        const string _VERSION_NUMBER = "0.3 (beta)";
        const string _PRODUCT_ID = "{1CF88B2C-9FB8-498E-96DD-9F97ACBACDA7}";
        const string _PRODUCT_ID_FAKE = "{2984F3F0-1C63-441D-B8AA-6C7FDCACFEB2}";
        const string _REGISTRY_KEY_NAME = "FishingSearch";
        const string _REGISTRY_KEY_VALUE = "ProductID";
        const string _APPLICATION_NAME = "Fishing Search";
        const string _RESTRICTION_MESSAGE = "Opzioni di ricerca disponibili solo per il modulo CANNE.";
        private bool _IsCacheEnabled_Canne = false;
        private object _lock = new object();
        private object _lockAll = new object();
        Dictionary<string, string> dictInfo = new Dictionary<string, string>();
        ConcurrentDictionary<string, string> concurDictCanne = new ConcurrentDictionary<string, string>();
        BassRodLimit _bassRodLimit = new BassRodLimit();
        BluefishRodLimit _bluefishRodLimit = new BluefishRodLimit();
        BoatRodLimit _boatRodLimit = new BoatRodLimit();
        private Rods rod;
        private ObservableCollection<Rods> _RodsCollection = new ObservableCollection<Rods>();
        private List<string> _stringListLaMincio = new List<string>();
        private List<string> _stringListLamiglas = new List<string>();
        private List<string> _StringListFalcon = new List<string>();
        private List<string> _StringListGameFish = new List<string>();
        private List<string> _stringListFisherLandia = new List<string>();
        private List<string> _UrlCSC = new List<string>();

        const string _HTML_TAG_PATTERN = "<.*?>";
        const decimal _OUNCE = 28.35m;
        const decimal _FOOT = 30.48m;
        const decimal _INCH = 2.54m;
        //CASTING
        private int _minCastingValue;
        private int _maxCastingValue;
        //LENGTH
        private int _minLengthValue;
        private int _maxLengthValue;
        //ACTION
        private bool? _actionFast;
        private bool? _actionExtraFast;
        private bool? _actionModFast;
        private bool? _actionModerate;
        //POWER
        private bool? _powerMedium;
        private bool? _powerMediumHeavy;
        private bool? _powerHeavy;
        private bool? _powerModHeavy;
        private bool? _powerExtraHeavy;
        //BRAND
        private string _brand;

        private int totRods = 0;
        private int totRodSites = 0;
        private ProgressWindow dlg;
        public static BackgroundWorker bw;
        public static AutoResetEvent _resetEvent = new AutoResetEvent(false);
        string separator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
        MessageInfo miWarning;
        searchOption _SEARCH_OPTION;

        public enum searchOption
        {
            //NOT SET
            __NOT_SET,

            //CANNE
            CANNE_SPIGOLA_COSTA,
            CANNE_SERRA_COSTA,
            CANNE_BARCA,

            //MULINELLI
            MULINELLI_SPIGOLA_COSTA,
            MULINELLI_SERRA_COSTA,
            MULINELLI_BARCA,

            //ARTIFICIALI
            ARTIFICIALI_LONG_JERK,
            ARTIFICIALI_POPPERS,
            ARTIFICIALI_JIGS_SILICONICI,

            //ALTRO
            ALTRO_TRECCIATI,
            ALTRO_NYLON,
            ALTRO_FLUOROCARBON
        };

        #endregion

        #region event handlers

        /// <summary>
        /// Search button: main entrance for the program 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            long time;
            string searchItemOption;
            //check user input for search
            if (!SetOption() || (expCanneSpigola.IsExpanded == false))
            {
                imgFishCentral.Visibility = System.Windows.Visibility.Visible;
                miWarning = new MessageInfo(_RESTRICTION_MESSAGE, this);
                miWarning.ShowDialog();
                return;
            }


            SetLimit();

            var timer = Stopwatch.StartNew();
            //Cleaning the collection of data
            _RodsCollection.Clear();
            DataContext = null;
            imgFishCentral.Visibility = System.Windows.Visibility.Visible;
            dataGridResults.Visibility = System.Windows.Visibility.Hidden;
            gridResults.Visibility = System.Windows.Visibility.Hidden;
            txtTrovate.Text = "";

#if DEBUG
            //Server=tcp:b1fi24gxdu.database.windows.net,1433;Database=FISHINGSEARCH;User ID=fishingsearch@b1fi24gxdu;Password={your_password_here};Trusted_Connection=False;Encrypt=True;Connection Timeout=30;
            //string connectionString = @"Data Source=PC-DEV\SQLEXPRESS;Integrated Security=True";
            string connectionString = @"Server=b1fi24gxdu.database.windows.net,1433;Database=FISHINGSEARCH;User ID=fishingsearch;Password=indmmeF1950eqdmpeA1947;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            using (SqlCommand command = new SqlCommand("SELECT * FROM FISHINGSEARCH.dbo.Catalogo WITH (NOLOCK)", con))
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    rod = new Rods(reader["Codice"].ToString(), reader["Marca"].ToString(), reader["Modello"].ToString(),
                                   reader["NumPezzi"].ToString(), reader["Lunghezza"].ToString(), reader["Casting"].ToString(),
                                   reader["Azione"].ToString(), reader["Anelli"].ToString(), reader["Peso"].ToString(), reader["Potenza"].ToString(), "", null);
                    //rod = new Rods(codice, marca, modello, pezzi, lunghezza, casting, azione, anelli, peso, potenza, prezzo, new Uri(url));
                    _RodsCollection.Add(rod);
                }
            }
            DataContext =
                   (from i in _RodsCollection
                    select new { i.Marca, i.Codice, i.Modello, i.Pezzi, i.Lunghezza, i.Casting, i.Anelli, i.Azione, i.Peso, i.Potenza, i.Prezzo, i.Link }).ToList();
            gridResults.Visibility = System.Windows.Visibility.Visible;
            dataGridResults.Visibility = System.Windows.Visibility.Visible;

            totRods = _RodsCollection.Count;
            searchItemOption = getSearchOption().ToLower();
            time = timer.ElapsedMilliseconds ;
            miWarning = new MessageInfo("Trovate " + totRods + " " + searchItemOption + "." + Environment.NewLine +
                                        "(Trascorsi " + time + " millisesecondi.)", this);
            miWarning.ShowDialog();

            return;

#endif
            /////////////////////////////
            //TEST NETWORK CONNECTION
            /////////////////////////////
            if (!isNetworkConnectionOK())
            {
                miWarning = new MessageInfo("Problemi di rete." + Environment.NewLine +
                "Verificare lo stato della connessione ad Internet.", this);
                miWarning.ShowDialog();
                return;
            }

            ////////////////////
            //BACKGROUNDWORKER
            ////////////////////
            bw = new BackgroundWorker();
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.RunWorkerAsync();


            /////////////////////////////////////
            // SHOW THE PROGRESS WINDOW UPDATED  
            // BY THE BACKGROUDWORKER
            /////////////////////////////////////
            ShowProgressWindow();


            //////////////////////////////////
            // IN CASE OF CANCELLATION OF 
            // BACKGROUDWORKER, EXIT 
            //////////////////////////////////
            if (bw.CancellationPending)
            {
                concurDictCanne.Clear();
                imgFishCentral.Visibility = System.Windows.Visibility.Visible;
                gridResults.Visibility = System.Windows.Visibility.Hidden;
                dataGridResults.Visibility = System.Windows.Visibility.Hidden;
                txtTrovate.Text = "N. oggetti trovati: 0";
                return;
            }


            ////////////////////////////////////
            // SHOW RESULT MESSAGE TO THE USER
            ////////////////////////////////////
            totRods = _RodsCollection.Count;
            totRodSites = _UrlCSC.Count;
            searchItemOption = getSearchOption().ToLower();
            time = timer.ElapsedMilliseconds / 1000;
            miWarning = new MessageInfo("Trovate " + totRods + " " + searchItemOption + "." + Environment.NewLine +
                                        "Ricerca effettuata su " + totRodSites + " pagine web." + Environment.NewLine +
                                        "(Trascorsi " + time + " secondi.)", this);
            miWarning.ShowDialog();


            ///////////////////////////
            // POPULATE DATA WITH LINQ 
            ///////////////////////////
            DataContext =
            (from i in _RodsCollection
             select new { i.Marca, i.Codice, i.Modello, i.Pezzi, i.Lunghezza, i.Casting, i.Anelli, i.Azione, i.Peso, i.Potenza, i.Prezzo, i.Link }).ToList();


            /////////////////////////////////
            // SET THE VISIBILITY OF RESULTS
            /////////////////////////////////
            if (totRods > 0)
            {
                gridResults.Visibility = System.Windows.Visibility.Visible;
                dataGridResults.Visibility = System.Windows.Visibility.Visible;
                txtTrovate.Text = "N. oggetti trovati: " + totRods.ToString();
            }
            else
            {
                imgFishCentral.Visibility = System.Windows.Visibility.Visible;
                gridResults.Visibility = System.Windows.Visibility.Hidden;
                dataGridResults.Visibility = System.Windows.Visibility.Hidden;
                txtTrovate.Text = "N. oggetti trovati: 0";
            }

            return;
        }

        private void OpzioniMulinelli_Click(object sender, RoutedEventArgs e)
        {
            miWarning = new MessageInfo(_RESTRICTION_MESSAGE, this);
            miWarning.ShowDialog();
        }

        private void OpzioniArtificiali_Click(object sender, RoutedEventArgs e)
        {
            miWarning = new MessageInfo(_RESTRICTION_MESSAGE, this);
            miWarning.ShowDialog();
        }

        private void OpzioniAltro_Click(object sender, RoutedEventArgs e)
        {
            miWarning = new MessageInfo(_RESTRICTION_MESSAGE, this);
            miWarning.ShowDialog();
        }

        private void DG_Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            Hyperlink link = e.OriginalSource as Hyperlink;
            Process.Start(link.NavigateUri.AbsoluteUri);
        }

        private void Esci_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void OpzioniCanne_Click(object sender, RoutedEventArgs e)
        {
            OptionsRod opt = new OptionsRod(_bassRodLimit, _bluefishRodLimit, _boatRodLimit);
            opt.OptionsRodUpdated += new OptionsRod.OptionsRodEventHandler(OptionsRod_Updated);
            opt.ShowDialog();
        }

        private void OptionsRod_Updated(object sender, OptionsRodEventArgs e)
        {
            ClearActionAndPower();

            //BASS ROD
            _bassRodLimit.MinCasting = e.MinCasting_BassRod;
            _bassRodLimit.MaxCasting = e.MaxCasting_BassRod;
            _bassRodLimit.MinLength = e.MinLength_BassRod;
            _bassRodLimit.MaxLength = e.MaxLength_BassRod;
            _bassRodLimit.ActionFast = e.ActionFast_BassRod;
            _bassRodLimit.ActionExtraFast = e.ActionExtraFast_BassRod;
            _bassRodLimit.PowerMedium = e.PowerMedium_BassRod;
            _bassRodLimit.PowerMedHeavy = e.PowerMedHeavy_BassRod;
            _bassRodLimit.Brand = e.Brand_BassRod;

            //BLUEFISH ROD
            _bluefishRodLimit.MinCasting = e.MinCasting_BluefishRod;
            _bluefishRodLimit.MaxCasting = e.MaxCasting_BluefishRod;
            _bluefishRodLimit.MinLength = e.MinLength_BluefishRod;
            _bluefishRodLimit.MaxLength = e.MaxLength_BluefishRod;
            _bluefishRodLimit.ActionFast = e.ActionFast_BluefishRod;
            _bluefishRodLimit.ActionModFast = e.ActionModFast_BluefishRod;
            _bluefishRodLimit.ActionModerate = e.ActionModerate_BluefishRod;
            _bluefishRodLimit.PowerHeavy = e.PowerHeavy_BluefishRod;
            _bluefishRodLimit.PowerModHeavy = e.PowerModHeavy_BluefishRod;
            _bluefishRodLimit.PowerExtraHeavy = e.PowerExtraHeavy_BluefishRod;
            _bluefishRodLimit.Brand = e.Brand_BluefishRod;

            //BOAT ROD
            _boatRodLimit.MinCasting = e.MinCasting_BoatRod;
            _boatRodLimit.MaxCasting = e.MaxCasting_BoatRod;
            _boatRodLimit.MinLength = e.MinLength_BoatRod;
            _boatRodLimit.MaxLength = e.MaxLength_BoatRod;
            _boatRodLimit.ActionModerate = e.ActionModerate_BoatRod;
            _boatRodLimit.PowerHeavy = e.PowerHeavy_BoatRod;
            _boatRodLimit.PowerExtraHeavy = e.PowerExtraHeavy_BoatRod;
            _boatRodLimit.Brand = e.Brand_BoatRod;

            switch (_SEARCH_OPTION)
            {
                case searchOption.CANNE_SPIGOLA_COSTA:
                    //CASTING
                    _minCastingValue = e.MinCasting_BassRod;
                    _maxCastingValue = e.MaxCasting_BassRod;
                    //LENGTH
                    _minLengthValue = e.MinLength_BassRod;
                    _maxLengthValue = e.MaxLength_BassRod;
                    //ACTION
                    _actionFast = e.ActionFast_BassRod;
                    _actionExtraFast = e.ActionExtraFast_BassRod;
                    //POWER
                    _powerMedium = e.PowerMedium_BassRod;
                    _powerMediumHeavy = e.PowerMedHeavy_BassRod;
                    //BRAND
                    _brand = e.Brand_BassRod;
                    break;

                case searchOption.CANNE_SERRA_COSTA:
                    //CASTING
                    _minCastingValue = e.MinCasting_BluefishRod;
                    _maxCastingValue = e.MaxCasting_BluefishRod;
                    //LENGTH
                    _minLengthValue = e.MinLength_BluefishRod;
                    _maxLengthValue = e.MaxLength_BluefishRod;
                    //ACTION
                    _actionFast = e.ActionFast_BluefishRod;
                    _actionModFast = e.ActionModFast_BluefishRod;
                    _actionModerate = e.ActionModerate_BluefishRod;
                    //POWER
                    _powerHeavy = e.PowerHeavy_BluefishRod;
                    _powerModHeavy = e.PowerModHeavy_BluefishRod;
                    _powerExtraHeavy = e.PowerExtraHeavy_BluefishRod;
                    //BRAND
                    _brand = e.Brand_BluefishRod;
                    break;

                case searchOption.CANNE_BARCA:
                    //CASTING
                    _minCastingValue = e.MinCasting_BoatRod;
                    _maxCastingValue = e.MaxCasting_BoatRod;
                    //LENGTH
                    _minLengthValue = e.MinLength_BoatRod;
                    _maxLengthValue = e.MaxLength_BoatRod;
                    //ACTION
                    _actionModerate = e.ActionModerate_BoatRod;
                    //POWER
                    _powerHeavy = e.PowerHeavy_BoatRod;
                    _powerExtraHeavy = e.PowerExtraHeavy_BoatRod;
                    //BRAND
                    _brand = e.Brand_BoatRod;
                    break;
            }
        }

        private void Info_Click(object sender, RoutedEventArgs e)
        {
            MessageInfo miWarning = new MessageInfo();
            miWarning.txtInfoMessage.Text = _APPLICATION_NAME + Environment.NewLine + Environment.NewLine +
                                            "Ricerca online delle canne da pesca" + Environment.NewLine +
                                            "Versione " + _VERSION_NUMBER;
            miWarning.Owner = this;
            miWarning.ShowDialog();
        }

        #endregion

        #region background worker

        /// <summary>
        /// SWITCHING THE WORK FOR BACKGROUDWORKER,  ACCORDING TO DIFFERENT OPTION SEARCH
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {

            switch (_SEARCH_OPTION)
            {

                case searchOption.CANNE_SPIGOLA_COSTA:
                case searchOption.CANNE_SERRA_COSTA:
                case searchOption.CANNE_BARCA:
                    doWork_Canne();
                    break;
                default:
                    throw new Exception("option not released!");
            }

        }

        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //progressBar.Value += 1;
            ////progressBar1.Value = e.ProgressPercentage;
            //lblStatus.Content = "Percentuale di completamento: " + e.ProgressPercentage + " %";//, min= " + dlg.progressBar.Minimum + ", MAX=" + dlg.progressBar.Maximum;
            //txtDialogMessage.Text = e.ProgressPercentage.ToString();
        }

        public void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //progressBar.Value = 100;
            //txtDialogMessage.Text = "Percentuale di completamento: 100%";
        }

        /// <summary>
        /// LOAD ALL URLS AND ITERATE THROUGH THEM 
        /// TO FIND THE CORRECT ITEMS
        /// </summary>
        public void doWork_Canne()
        {
            //RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\My_app", true);


            if (!_IsCacheEnabled_Canne)
            {
                //GetInfoCSC();
                _UrlCSC = LoadAllHref();
                GetAndStoreHTML(_UrlCSC, concurDictCanne);
                _IsCacheEnabled_Canne = true;
            }

            Action action = new Action(() =>
            {
                dlg.progressBar.Value = dlg.progressBar.Maximum;
                //dlg.txtDialogMessage.Text = "Ricerca in corso..." + Environment.NewLine + "Canne da Spigola dalla Costa";
                dlg.lblStatus.Content = "Percentuale di completamento: 100 %";
            }
            );
            this.Dispatcher.Invoke(action, DispatcherPriority.ApplicationIdle);


            //var timeAll = timer.ElapsedMilliseconds;
            //MessageBox.Show("Elapsed " + timeAll + " seconds.");

            FilterData_Canne(concurDictCanne);


            Action act = new Action(() =>
            {
                dlg.Close();
            }
            );
            this.Dispatcher.Invoke(act, DispatcherPriority.ApplicationIdle);

        }

        #endregion

        #region utility

        private string GetDomainFromUrl(string url)
        {
            if (url == "")
                return "";
            try
            {
                url = url.Replace("http://", "");
                int i = url.IndexOf("/");
                return url.Substring(0, i);
            }
            catch (Exception)
            {
                return "";
            }

        }

        private string GetDomainNameFromUrl(string url)
        {
            if (url == "")
                return "";
            try
            {
                url = url.Replace("http://www.", "");
                int i = url.IndexOf(".");
                return url.Substring(0, i);
            }
            catch (Exception)
            {
                return "";
            }
        }

        private void SetLimit()
        {
            ClearActionAndPower();

            switch (_SEARCH_OPTION)
            {
                case searchOption.CANNE_SPIGOLA_COSTA:
                    _minCastingValue = _bassRodLimit.MinCasting;
                    _maxCastingValue = _bassRodLimit.MaxCasting;
                    _minLengthValue = _bassRodLimit.MinLength;
                    _maxLengthValue = _bassRodLimit.MaxLength;
                    _actionFast = _bassRodLimit.ActionFast;
                    _actionExtraFast = _bassRodLimit.ActionExtraFast;
                    _powerMedium = _bassRodLimit.PowerMedium;
                    _powerMediumHeavy = _bassRodLimit.PowerMedHeavy;
                    _brand = _bassRodLimit.Brand;
                    break;
                case searchOption.CANNE_SERRA_COSTA:
                    _minCastingValue = _bluefishRodLimit.MinCasting;
                    _maxCastingValue = _bluefishRodLimit.MaxCasting;
                    _minLengthValue = _bluefishRodLimit.MinLength;
                    _maxLengthValue = _bluefishRodLimit.MaxLength;
                    _actionFast = _bluefishRodLimit.ActionFast;
                    _actionModFast = _bluefishRodLimit.ActionModFast;
                    _actionModerate = _bluefishRodLimit.ActionModerate;
                    _powerHeavy = _bluefishRodLimit.PowerHeavy;
                    _powerModHeavy = _bluefishRodLimit.PowerModHeavy;
                    _powerExtraHeavy = _bluefishRodLimit.PowerExtraHeavy;
                    _brand = _bluefishRodLimit.Brand;
                    break;
                case searchOption.CANNE_BARCA:
                    _minCastingValue = _boatRodLimit.MinCasting;
                    _maxCastingValue = _boatRodLimit.MaxCasting;
                    _minLengthValue = _boatRodLimit.MinLength;
                    _maxLengthValue = _boatRodLimit.MaxLength;
                    _actionModerate = _boatRodLimit.ActionModerate;
                    _powerHeavy = _boatRodLimit.PowerHeavy;
                    _powerExtraHeavy = _boatRodLimit.PowerExtraHeavy;
                    _brand = _boatRodLimit.Brand;
                    break;
                case searchOption.MULINELLI_SPIGOLA_COSTA:
                    break;
                case searchOption.MULINELLI_SERRA_COSTA:
                    break;
                case searchOption.MULINELLI_BARCA:
                    break;
                case searchOption.ARTIFICIALI_LONG_JERK:
                    break;
                case searchOption.ARTIFICIALI_POPPERS:
                    break;
                case searchOption.ARTIFICIALI_JIGS_SILICONICI:
                    break;
                case searchOption.ALTRO_TRECCIATI:
                    break;
                case searchOption.ALTRO_NYLON:
                    break;
                case searchOption.ALTRO_FLUOROCARBON:
                    break;
                default:
                    break;
            }

        }

        private bool SetOption()
        {

            if (rdbCanneSpigola.IsChecked == true)
            {
                _SEARCH_OPTION = searchOption.CANNE_SPIGOLA_COSTA;
                return true;
            }
            if (rdbCanneSerra.IsChecked == true)
            {
                _SEARCH_OPTION = searchOption.CANNE_SERRA_COSTA;
                return true;
            }
            if (rdbCanneBarca.IsChecked == true)
            {
                _SEARCH_OPTION = searchOption.CANNE_BARCA;
                return true;
            }
            //_SEARCH_OPTION = null;
            return false;

        }

        private string getSearchOption()
        {
            switch (_SEARCH_OPTION)
            {
                case searchOption.CANNE_SPIGOLA_COSTA:
                    return "CANNE DA SPIGOLA DALLA COSTA";
                case searchOption.CANNE_SERRA_COSTA:
                    return "CANNE DA SERRA DALLA COSTA";
                case searchOption.CANNE_BARCA:
                    return "CANNE DA BARCA";
                case searchOption.MULINELLI_SPIGOLA_COSTA:
                    return "MULINELLI DA SPIGOLA DALLA COSTA";
                case searchOption.MULINELLI_SERRA_COSTA:
                    return "MULINELLI DA SERRA DALLA COSTA";
                case searchOption.MULINELLI_BARCA:
                    return "MULINELLI DA BARCA";
                case searchOption.ARTIFICIALI_LONG_JERK:
                    return "ARTIFICIALI LONG JERK";
                case searchOption.ARTIFICIALI_POPPERS:
                    return "ARTIFICIALI POPPERS";
                case searchOption.ARTIFICIALI_JIGS_SILICONICI:
                    return "ARTIFICIALI JIGS SILICONICI";
                case searchOption.ALTRO_TRECCIATI:
                    return "TRECCIATI";
                case searchOption.ALTRO_NYLON:
                    return "NYLON";
                case searchOption.ALTRO_FLUOROCARBON:
                    return "FLUOROCARBON";
                default:
                    return "";
            }
        }


        /// <summary>
        /// SHOW THE PROGRESS WINDOW IN DIALOG MODE 
        /// AND WAIT FOR THE BACKGROUNDWORKER 
        /// </summary>
        private void ShowProgressWindow()
        {
            string searchItemOption = getSearchOption();
            dlg = new ProgressWindow();
            dlg.Owner = this;
            dlg.txtDialogMessage.Text += Environment.NewLine + searchItemOption;
            dlg.ShowDialog();
        }


        /// <summary>
        /// CHECK THE NETWORK CONNECTION
        /// </summary>
        private bool isNetworkConnectionOK()
        {
            try
            {
                var testNetworkConnection = WebRequest.Create("http://www.google.it").GetResponse();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }


        private string FindValueInsideString(string item, string chekValue, out bool isFound)
        {
            string value = RemoveTags(item).Trim();
            string retValue = "";
            isFound = false;
            if (value.StartsWith(chekValue))
            {
                retValue = value.Replace(chekValue, "").Trim();
                isFound = true;
            }
            return retValue;
        }

        private string ConvertUrlsToLinks(string msg)
        {
            string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
            Regex r = new Regex(regex, RegexOptions.IgnoreCase);
            return r.Replace(msg, "<a href=\"$1\" title=\"Click to open in a new window or tab\" target=\"&#95;blank\">$1</a>").Replace("href=\"www", "href=\"http://www");
        }

        private string RemoveTags(string str)
        {
            //Regex re = new Regex("[\r\n\t]", RegexOptions.Compiled);
            str = str.Replace("\r", "").Replace("\n", "").Replace("\t", "");
            return Regex.Replace(str, _HTML_TAG_PATTERN, string.Empty);
        }

        #endregion

        #region initialize data

        private List<string> LoadAllHref()
        {
            var time = Stopwatch.StartNew();
            string staticUrl;
            var stringListAll = new List<string>();


            staticUrl = "http://www.superfish.it/canne/lamiglas/lamiglas_canne.jsp";
            stringListAll.Add(staticUrl + "");

#if !FAST_TEST
            //LA MINCIO
            staticUrl = "http://www.lamincio.com/nqcontent.cfm?a_id=";
            //ABU GARCIA
            stringListAll.Add(staticUrl + "5602");
            stringListAll.Add(staticUrl + "5603");
            //ALCEDO
            stringListAll.Add(staticUrl + "7163");
            stringListAll.Add(staticUrl + "7187");
            stringListAll.Add(staticUrl + "4350");
            stringListAll.Add(staticUrl + "7143");
            stringListAll.Add(staticUrl + "7144");
            stringListAll.Add(staticUrl + "7145");
            //BERKLEY
            stringListAll.Add(staticUrl + "9471");
            stringListAll.Add(staticUrl + "9470");
            stringListAll.Add(staticUrl + "7217");
            //DAIWA
            stringListAll.Add(staticUrl + "5152");
            stringListAll.Add(staticUrl + "9568");
            stringListAll.Add(staticUrl + "8317");
            stringListAll.Add(staticUrl + "8318");
            stringListAll.Add(staticUrl + "8398");
            //FOX
            stringListAll.Add(staticUrl + "4503");
            //FOX RAGE
            stringListAll.Add(staticUrl + "8539");
            stringListAll.Add(staticUrl + "8540");
            stringListAll.Add(staticUrl + "8541");
            stringListAll.Add(staticUrl + "8542");
            stringListAll.Add(staticUrl + "8543");
            stringListAll.Add(staticUrl + "8544");
            stringListAll.Add(staticUrl + "8553");
            stringListAll.Add(staticUrl + "8554");
            //G-LOOMIS OUTLET
            stringListAll.Add(staticUrl + "9502");
            //G-LOOMIS
            stringListAll.Add(staticUrl + "9511");
            stringListAll.Add(staticUrl + "9513");
            stringListAll.Add(staticUrl + "9512");
            stringListAll.Add(staticUrl + "9514");
            stringListAll.Add(staticUrl + "9518");
            stringListAll.Add(staticUrl + "6963");
            stringListAll.Add(staticUrl + "5239");
            stringListAll.Add(staticUrl + "5242");
            stringListAll.Add(staticUrl + "5243");
            stringListAll.Add(staticUrl + "5245");
            stringListAll.Add(staticUrl + "5263");
            stringListAll.Add(staticUrl + "5301");
            stringListAll.Add(staticUrl + "5303");
            stringListAll.Add(staticUrl + "5305");
            stringListAll.Add(staticUrl + "5306");
            stringListAll.Add(staticUrl + "5419");
            //MAJOR CRAFT
            stringListAll.Add(staticUrl + "8442");
            stringListAll.Add(staticUrl + "7590");
            stringListAll.Add(staticUrl + "8443");
            stringListAll.Add(staticUrl + "7763");
            stringListAll.Add(staticUrl + "7764");
            //MITCHELL
            stringListAll.Add(staticUrl + "9564");
            //PEZON E MICHEL
            stringListAll.Add(staticUrl + "2104");
            //SAVAGE GEAR
            stringListAll.Add(staticUrl + "7771");
            stringListAll.Add(staticUrl + "5891");
            stringListAll.Add(staticUrl + "8955");
            //SHIMANO
            stringListAll.Add(staticUrl + "9296");
            stringListAll.Add(staticUrl + "5492");
            stringListAll.Add(staticUrl + "7949");
            stringListAll.Add(staticUrl + "5501");
            stringListAll.Add(staticUrl + "6990");
            stringListAll.Add(staticUrl + "5494");
            stringListAll.Add(staticUrl + "6987");
            stringListAll.Add(staticUrl + "9314");
            stringListAll.Add(staticUrl + "9112");
            stringListAll.Add(staticUrl + "9111");
            stringListAll.Add(staticUrl + "7951");
            stringListAll.Add(staticUrl + "7952");
            stringListAll.Add(staticUrl + "7958");
            stringListAll.Add(staticUrl + "5495");
            stringListAll.Add(staticUrl + "6988");
            stringListAll.Add(staticUrl + "6989");
            stringListAll.Add(staticUrl + "7959");
            stringListAll.Add(staticUrl + "5500");
            //SHIMANO YASEI
            stringListAll.Add(staticUrl + "9108");
            stringListAll.Add(staticUrl + "9109");
            stringListAll.Add(staticUrl + "9297");
            //ST CROIX
            stringListAll.Add(staticUrl + "9299");
            stringListAll.Add(staticUrl + "7297");
            stringListAll.Add(staticUrl + "9142");
            stringListAll.Add(staticUrl + "7021");
            stringListAll.Add(staticUrl + "7928");
            stringListAll.Add(staticUrl + "7019");
            stringListAll.Add(staticUrl + "9794");
            stringListAll.Add(staticUrl + "7830");
            stringListAll.Add(staticUrl + "9796");
            stringListAll.Add(staticUrl + "9797");
            stringListAll.Add(staticUrl + "7022");
            stringListAll.Add(staticUrl + "7298");
            stringListAll.Add(staticUrl + "7926");
            stringListAll.Add(staticUrl + "7020");
            stringListAll.Add(staticUrl + "7827");
            stringListAll.Add(staticUrl + "7015");
            stringListAll.Add(staticUrl + "7081");
            stringListAll.Add(staticUrl + "7142");
            stringListAll.Add(staticUrl + "7023");
            stringListAll.Add(staticUrl + "8989");
            stringListAll.Add(staticUrl + "9786");
            stringListAll.Add(staticUrl + "9785");

            //LAMIGLAS
            staticUrl = "http://www.lamiglas.com/prod_indiv.php?groupid=";
            stringListAll.Add(staticUrl + "53");
            //SALTWATER RODS: BLACK SALT
            stringListAll.Add(staticUrl + "79");
            //SALTWATER RODS: BIG FISH
            stringListAll.Add(staticUrl + "32");
            //SALTWATER RODS: EXCEL INSHORE
            stringListAll.Add(staticUrl + "69");
            //SALTWATER RODS: TRI-FLEX GRAPHITE SALTWATER
            stringListAll.Add(staticUrl + "30");

            //FALCONRODSITALY
            staticUrl = "http://www.falconrodsitaly.com/";
            stringListAll.Add(staticUrl + "falcon_cara_t7.php");
            stringListAll.Add(staticUrl + "falcon_bucoo.php");
            stringListAll.Add(staticUrl + "falcon_lowrider.php");
            stringListAll.Add(staticUrl + "falcon_original.php");
            stringListAll.Add(staticUrl + "falcon_hd.php");


            //GAMEIFISH
            staticUrl = "http://www.gamefish.it/index.php?page=shop.product_details&flypage=flypage.tpl&product_id=";
            // ST. CROIX AVID INSHORE 
            stringListAll.Add(staticUrl + "4328&category_id=530&option=com_virtuemart&Itemid=254");
            stringListAll.Add(staticUrl + "4329&category_id=530&option=com_virtuemart&Itemid=254");
            stringListAll.Add(staticUrl + "4330&category_id=530&option=com_virtuemart&Itemid=254");
            stringListAll.Add(staticUrl + "6000&category_id=530&option=com_virtuemart&Itemid=254");
            stringListAll.Add(staticUrl + "4332&category_id=530&option=com_virtuemart&Itemid=254");
            //ST. CROIX TIDEMASTER INSHORE 
            stringListAll.Add(staticUrl + "7505&category_id=531&option=com_virtuemart&Itemid=254");
            stringListAll.Add(staticUrl + "7796&category_id=531&option=com_virtuemart&Itemid=254");
            stringListAll.Add(staticUrl + "7504&category_id=531&option=com_virtuemart&Itemid=254");
            stringListAll.Add(staticUrl + "7509&category_id=531&option=com_virtuemart&Itemid=254");
            // ST. CROIX MOJO INSHORE 
            stringListAll.Add(staticUrl + "7795&category_id=555&option=com_virtuemart&Itemid=254");
            stringListAll.Add(staticUrl + "7794&category_id=555&option=com_virtuemart&Itemid=254");

            //FISHERLANDIA
            staticUrl = "http://www.fisherlandia.it/";
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=1126&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=552&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=836&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=962&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=125&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=850&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=829&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=937&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=126&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=130&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=956&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=833&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=959&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=123&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=960&mar=1&catalog=0");
            stringListAll.Add(staticUrl + "catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=831&mar=1&catalog=0");

            staticUrl = "http://www.gloomis.com/";
            stringListAll.Add(staticUrl + "publish/content/gloomis_2010/eu/en/conventional/rods/classic_bass_rods/classic_spin_jig.html");
            stringListAll.Add(staticUrl + "publish/content/gloomis_2010/eu/en/conventional/rods/saltwater_rods/pro-green.html");
#endif

            //var timeElapsed = time.ElapsedMilliseconds;
            //MessageBox.Show("LoadAllHref -- elapsed:" + timeElapsed.ToString());
            return stringListAll;
        }

        private List<string> LoadHrefLamincio()
        {
            var stringList = new List<string>();

            //stringList.Add("8989");
            //return stringList;
            //htBrand

            //ABU GARCIA
            stringList.Add("5602");
            stringList.Add("5603");

            //ALCEDO
            stringList.Add("7163");
            stringList.Add("7187");
            stringList.Add("4350");
            stringList.Add("7143");
            stringList.Add("7144");
            stringList.Add("7145");

            //BERKLEY
            stringList.Add("9471");
            stringList.Add("9470");
            stringList.Add("7217");

            //DAIWA
            stringList.Add("5152");
            stringList.Add("9568");
            stringList.Add("8317");
            stringList.Add("8318");
            stringList.Add("8398");

            //FOX
            stringList.Add("4503");

            //FOX RAGE
            stringList.Add("8539");
            stringList.Add("8540");
            stringList.Add("8541");
            stringList.Add("8542");
            stringList.Add("8543");
            stringList.Add("8544");
            stringList.Add("8553");
            stringList.Add("8554");

            //G-LOOMIS OUTLET
            stringList.Add("9502");

            //G-LOOMIS
            stringList.Add("9511");
            stringList.Add("9513");
            stringList.Add("9512");
            stringList.Add("9514");
            stringList.Add("9518");
            stringList.Add("6963");
            stringList.Add("5239");
            stringList.Add("5242");
            stringList.Add("5243");
            stringList.Add("5245");
            stringList.Add("5263");
            stringList.Add("5301");
            stringList.Add("5303");
            stringList.Add("5305");
            stringList.Add("5306");
            stringList.Add("5419");

            //MAJOR CRAFT
            stringList.Add("8442");
            stringList.Add("7590");
            stringList.Add("8443");
            stringList.Add("7763");
            stringList.Add("7764");

            //MITCHELL
            stringList.Add("9564");

            //PEZON E MICHEL
            stringList.Add("2104");

            //SAVAGE GEAR
            stringList.Add("7771");
            stringList.Add("5891");
            stringList.Add("8955");

            //SHIMANO
            stringList.Add("9296");
            stringList.Add("5492");
            stringList.Add("7949");
            stringList.Add("5501");
            stringList.Add("6990");
            stringList.Add("5494");
            stringList.Add("6987");
            stringList.Add("9314");
            stringList.Add("9112");
            stringList.Add("9111");
            stringList.Add("7951");
            stringList.Add("7952");
            stringList.Add("7958");
            stringList.Add("5495");
            stringList.Add("6988");
            stringList.Add("6989");
            stringList.Add("7959");
            stringList.Add("5500");

            //SHIMANO YASEI
            stringList.Add("9108");
            stringList.Add("9109");
            stringList.Add("9297");

            //ST CROIX
            stringList.Add("9299");
            stringList.Add("7297");
            stringList.Add("9142");
            stringList.Add("7021");
            stringList.Add("7928");
            stringList.Add("7019");
            stringList.Add("9794");
            stringList.Add("7830");
            stringList.Add("9796");
            stringList.Add("9797");
            stringList.Add("7022");
            stringList.Add("7298");
            stringList.Add("7926");
            stringList.Add("7020");
            stringList.Add("7827");
            stringList.Add("7015");
            stringList.Add("7081");
            stringList.Add("7142");
            stringList.Add("7023");
            stringList.Add("8989");
            stringList.Add("9786");
            stringList.Add("9785");


            return stringList;
        }

        private List<string> LoadHrefLamiglas()
        {
            var stringList = new List<string>();

            stringList.Add("53");

            //SALTWATER RODS: BLACK SALT
            stringList.Add("79");

            //SALTWATER RODS: BIG FISH
            stringList.Add("32");

            //SALTWATER RODS: EXCEL INSHORE
            stringList.Add("69");

            //SALTWATER RODS: TRI-FLEX GRAPHITE SALTWATER
            stringList.Add("30");

            return stringList;
        }

        private List<string> LoadHrefFalcon()
        {
            var stringList = new List<string>();


            stringList.Add("falcon_cara_t7.php");

            //
            stringList.Add("falcon_bucoo.php");

            //
            stringList.Add("falcon_lowrider.php");

            //
            stringList.Add("falcon_original.php");

            //
            stringList.Add("falcon_hd.php");

            return stringList;
        }

        private List<string> LoadHrefGameFish()
        {
            var stringList = new List<string>();

            // ST. CROIX AVID INSHORE 
            stringList.Add("4328&category_id=530&option=com_virtuemart&Itemid=254");
            stringList.Add("4329&category_id=530&option=com_virtuemart&Itemid=254");
            stringList.Add("4330&category_id=530&option=com_virtuemart&Itemid=254");
            stringList.Add("6000&category_id=530&option=com_virtuemart&Itemid=254");
            stringList.Add("4332&category_id=530&option=com_virtuemart&Itemid=254");

            //ST. CROIX TIDEMASTER INSHORE 
            stringList.Add("7505&category_id=531&option=com_virtuemart&Itemid=254");
            stringList.Add("7796&category_id=531&option=com_virtuemart&Itemid=254");
            stringList.Add("7504&category_id=531&option=com_virtuemart&Itemid=254");
            stringList.Add("7509&category_id=531&option=com_virtuemart&Itemid=254");

            // ST. CROIX MOJO INSHORE 
            stringList.Add("7795&category_id=555&option=com_virtuemart&Itemid=254");
            stringList.Add("7794&category_id=555&option=com_virtuemart&Itemid=254");


            return stringList;
        }

        private List<string> LoadHrefFisherLandia()
        {
            var stringList = new List<string>();

            // 
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=1126&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=552&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=836&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=962&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=125&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=850&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=829&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=937&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=126&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=130&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=956&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=833&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=959&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=123&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=960&mar=1&catalog=0");
            stringList.Add("catalogo.php?id=classepro2&rid=catalogo&cat=2&tip=17&id_clp=831&mar=1&catalog=0");
            return stringList;
        }

        #endregion

        #region search information

        /// <summary>
        /// FILTER THE DATA RECEIVED AND ADD TO THE COMMON DATA STRUCTURE
        /// </summary>
        /// <param name="concurrentDictCanneSpigolaCosta"></param>
        private void FilterData_Canne(ConcurrentDictionary<string, string> concurrentDictCanneSpigolaCosta)
        {

            //http://www.lamincio.com
            //http://www.lamiglas.com
            //http://www.falconrodsitaly.com

            //http://www.gamefish.it
            //http://www.fisherlandia.it
            //http://www.gloomis.com/
            //#warning uncomment here...
            //foreach (var pair in concurrentDictCanneSpigolaCosta)
            Parallel.ForEach(concurrentDictCanneSpigolaCosta, pair =>
            {

                string url = pair.Key;
                string html = pair.Value;

                url = url.Replace("http://www.", "").Replace(".com", "").ToUpper();

                if (url.StartsWith("GLOOMIS"))
                {
                    GetInfoGloomisFast(html, pair.Key);
                }
                else if (url.StartsWith("FISHERLANDIA"))
                {
                    GetInfoFisherLandiaFast(html, pair.Key);
                }
                else if (url.StartsWith("GAMEFISH"))
                {
                    GetInfoGameFishFast(html, pair.Key);
                }
                else if (url.StartsWith("FALCONRODSITALY"))
                {
                    GetInfoFalconRodsItalyFast(html, pair.Key);
                }
                else if (url.StartsWith("LAMIGLAS"))
                {
                    GetInfoLamiglasFast(html, pair.Key);
                }
                else if (url.StartsWith("LAMINCIO"))
                {
                    GetInfoLaMincioFast(html, pair.Key);
                }
                else if (url.StartsWith("SUPERFISH"))
                {
                    GetInfoSuperfishFast(html, pair.Key);
                }
                //switch (url)
                //{
                //    case "GLOOMIS":
                //        break;

                //}
            }
            );

        }

        private void GetAndStoreHTML(List<string> urls, ConcurrentDictionary<string, string> concurrentDict)
        {

            Action act = new Action(() =>
            {
                dlg.progressBar.Minimum = 0;
                dlg.progressBar.Maximum = urls.Count;
                dlg.btnCancel.Visibility = Visibility.Visible;
            }
            );

            this.Dispatcher.Invoke(act, DispatcherPriority.ApplicationIdle);



            Parallel.ForEach(urls, url =>
            {

                using (var response = WebRequest.Create(url).GetResponse())
                {
                    StreamReader reader = null;
                    string resultHTML;
                    reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    resultHTML = reader.ReadToEnd();

                    //lock (_lockAll)
                    //{
                    //dictInfo.Add(url, resultHTML);
                    concurrentDict.TryAdd(url, resultHTML);
                    Action action = new Action(() =>
                    {
                        int actualPercentage;
                        dlg.progressBar.Value += 1;
                        //dlg.progressBar1.Value = dictInfo.Count;
                        //dlg.txtDialogMessage.Text = "Ricerca in corso: " + Environment.NewLine + searchItemDialog;
                        actualPercentage = (int)((dlg.progressBar.Value / dlg.progressBar.Maximum) * 100);
                        dlg.lblStatus.Content = "Percentuale di completamento: " + actualPercentage + " %";
                    }
                    );

                    this.Dispatcher.Invoke(action, DispatcherPriority.ApplicationIdle);
                    //}
                }
            }
            );

        }

        private void GetInfoLamiglasFast(string html, string url)
        {

            string codice = "-";
            string marca = "LAMIGLAS";
            string modello = "-";
            string pezzi = "-";
            string lunghezza = "-";
            string casting = "-";
            string anelli = "-";
            string peso = "-";
            string azione = "-";
            string potenza = "-";
            //double prezzo = 0;
            string prezzo = "-";
            int columnNum = 0;

            try
            {

                //HtmlAgilityPack...
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.OptionAutoCloseOnEnd = true;
                doc.OptionFixNestedTags = true;
                doc.OptionCheckSyntax = false;
                doc.OptionOutputAsXml = true;
                doc.OptionDefaultStreamEncoding = Encoding.Default;
                doc.LoadHtml(html);
                HtmlAgilityPack.HtmlNode root = doc.DocumentNode;

                HtmlAgilityPack.HtmlNode htmlNodeColumnNum = doc.DocumentNode.SelectSingleNode("//table[@class='tablesorter']");
                if (htmlNodeColumnNum != null)
                {
                    columnNum = htmlNodeColumnNum.Descendants("th").Count();
                    //var columnlist = new string[columnNum];
                    var columnlist = new string[columnNum];
                    int index = 0;
                    foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumnNum.Descendants("th"))
                    {
                        columnlist[index] = RemoveTags(node.InnerText).ToUpper().Trim();
                        index += 1;
                    }
                    //replace the "Buy Now" column without the corresponding value to correctly find it later
                    columnlist[--columnNum] = "BUY NOW";

                    //"odd" or "even" are the only way to find all the rows of table
                    //HtmlAgilityPack.HtmlNodeCollection htmlNodeColumn = doc.DocumentNode.SelectNodes("//tr[@class='odd']|//tr[@class='even']");

                    //int counter = 0;
                    string value;
                    HtmlAgilityPack.HtmlNodeCollection htmlNodeColumn;

                    //"odd" or "even" are the only way to find all the rows of table
                    //HtmlAgilityPack.HtmlNodeCollection htmlNodeColumn = doc.DocumentNode.SelectNodes("//tr[@class='odd']|//tr[@class='even']");
                    htmlNodeColumn = doc.DocumentNode.SelectNodes("//tr[@class='even']");
                    //counter = 0;
                    value = "";

                    //for (int i = 1; i <= 2; i++)
                    //{
                    //loop for the 2 class: "odd" and "even"
                    int counter = 0;
                    //if (i == 2)
                    //{
                    //    htmlNodeColumn = doc.DocumentNode.SelectNodes("//tr[@class='odd']");
                    //}

                    foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumn.Descendants("td"))
                    {
                        value = RemoveTags(node.InnerText).Trim();//.Replace("&#<span class="new2009">NEW!</span></p>;", "")
                        switch (columnlist[counter])
                        {
                            case "CODICE":
                            case "ITEM #":
                            case "SPINNING":
                            case "CASTING":
                                codice = value;
                                //clm.Codice = value;
                                counter += 1;
                                break;
                            case "MODELLO":
                            case "MODEL":
                                modello = value;
                                //clm.Modello = value;
                                counter += 1;
                                break;
                            case "PEZZI":
                            case "PIECES":
                            case "PCS.":
                                pezzi = value;
                                //clm.Pezzi = value;
                                counter += 1;
                                break;
                            case "LUNGHEZZA":
                            case "ROD LENGTH":
                            case "LENGTH":
                                lunghezza = value;
                                //clm.Lunghezza = value;
                                counter += 1;
                                break;
                            case "POTENZA":
                            case "POWER":
                                potenza = value.ToUpper();
                                //    //clm.Casting = value;
                                counter += 1;
                                break;
                            case "ANELLI":
                                anelli = value;
                                //clm.Anelli = value;
                                counter += 1;
                                break;
                            case "PESO":
                            case "LURE WEIGHT":
                            case "LURE WT.":
                                //valori invertiti
                                casting = value;
                                //peso = value;
                                //clm.Peso = value;
                                counter += 1;
                                break;
                            case "AZIONE":
                            case "ACTION":
                                //case "ACTION":
                                azione = value.ToUpper();
                                //clm.Azione = value;
                                counter += 1;
                                break;
                            //case "PREZZO":
                            //case "POTENZA":
                            //case "POWER":
                            case "MSRP":
                                //valore non corretto, commento!
                                //casting = value;
                                //clm.Casting = value;

                                //break;
                                //value = value.Replace("Euro", "").Replace(".", ",").Replace("$","");

                                //prezzo = Convert.ToDouble(DeleteRebateFromPrice(value));
                                //prezzo = 0;
                                prezzo = value.Replace("$", "") + " dollari";
                                counter += 1;
                                break;
                            case "BUY NOW":

                                // TODO : UNCOMMENT BELOW CHECK
                                if (CheckValueCastingLureWeight(casting) && CheckValueLengthStandard(lunghezza) && CheckValueAction(azione) && CheckValuePower(potenza) && CheckValueBrand(marca))
                                {
                                    rod = new Rods(codice, marca, modello, pezzi, lunghezza, casting, azione, anelli, peso, potenza, prezzo, new Uri(url));
                                    lock (_lock)
                                    {
                                        _RodsCollection.Add(rod);
                                    }
                                }
                                //clm = new CanneLaMincio(info);
                                //info.clearInfo(info);
                                codice = "-";
                                modello = "-";
                                pezzi = "-";
                                lunghezza = "-";
                                casting = "-";
                                anelli = "-";
                                peso = "-";
                                azione = "-";
                                counter = 0;
                                break;
                            default:
                                counter += 1;
                                break;
                        }
                    }

                    //}//for
                }
            }


            catch (Exception)
            {
                // error handling
#if VERBOSE_MODE
                MessageBox.Show(ex.Message);
                throw new Exception("URL" + url);
#endif
            }
            finally
            {
                //if (reader != null)
                //    reader.Close();
                //if (response != null)
                //    response.Close();
            }

        }

        private void GetInfoGameFishFast(string html, string url)
        {

            string marca = "-";
            string codice = "-";
            string modello = "-";
            string pezzi = "-";
            string lunghezza = "-";
            string casting = "-";
            string anelli = "-";
            string peso = "-";
            string azione = "-";
            string potenza = "-";
            //double prezzo = 0;
            string prezzo = "-";


            try
            {

                //HtmlAgilityPack...
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.OptionAutoCloseOnEnd = true;
                doc.OptionFixNestedTags = true;
                doc.OptionCheckSyntax = false;
                doc.OptionOutputAsXml = true;
                doc.OptionDefaultStreamEncoding = Encoding.Default;
                doc.LoadHtml(html);
                HtmlAgilityPack.HtmlNode root = doc.DocumentNode;

                HtmlAgilityPack.HtmlNodeCollection htmlNodeHeaders = doc.DocumentNode.SelectNodes("//h1");
                HtmlAgilityPack.HtmlNode htmlNodePrice = doc.DocumentNode.SelectSingleNode("//span[@class='productPrice']");
                HtmlAgilityPack.HtmlNodeCollection htmlNodeValues = doc.DocumentNode.SelectNodes("//span");

                bool marcaTrovato = false;
                bool modelloTrovato = false;
                bool lunghezzaTrovato = false;
                bool castingTrovato = false;
                bool azioneTrovato = false;
                bool potenzaTrovato = false;
                bool pesoTrovato = false;
                bool codiceTrovato = false;

                foreach (HtmlAgilityPack.HtmlNode node in htmlNodeValues)
                {
                    if (!marcaTrovato)
                    {
                        marca = FindValueInsideString(node.InnerText, "Marca:", out marcaTrovato);
                    }

                    if (!modelloTrovato)
                    {
                        modello = FindValueInsideString(node.InnerText, "Modello:", out modelloTrovato);
                    }

                    if (!lunghezzaTrovato)
                    {
                        lunghezza = FindValueInsideString(node.InnerText, "Lunghezza:", out lunghezzaTrovato);
                    }

                    if (!castingTrovato)
                    {
                        casting = FindValueInsideString(node.InnerText, "Casting Weight:", out castingTrovato);
                    }

                    if (!azioneTrovato)
                    {
                        azione = FindValueInsideString(node.InnerText, "Azione:", out azioneTrovato);
                    }

                    if (!potenzaTrovato)
                    {
                        potenza = FindValueInsideString(node.InnerText, "Power:", out potenzaTrovato);
                    }

                    if (!pesoTrovato)
                    {
                        peso = FindValueInsideString(node.InnerText, "Peso:", out pesoTrovato);
                    }
                }

                foreach (HtmlAgilityPack.HtmlNode node in htmlNodeHeaders)
                {
                    if (!codiceTrovato)
                    {
                        codice = FindValueInsideString(node.InnerText.Trim().Replace(" ", ""), marca.Replace(" ", "") + modello.Replace(" ", ""), out codiceTrovato);
                    }
                }

                if (codiceTrovato && modello.Length > 0)
                {
                    codice = codice.Replace(modello, "");
                }
                //codice = htmlNodeHeader.InnerText.Replace(marca + modello, "");

                prezzo = htmlNodePrice.InnerText.Trim().Replace("&euro;", "");
                if (marca.Length > 0)
                { marca = marca.ToUpper(); }

                if (CheckValueCasting(casting) && CheckValueLengthStandard(lunghezza) && CheckValueAction(azione) && CheckValuePower(potenza) && CheckValueBrand(marca))
                {
                    rod = new Rods(codice, marca, modello, pezzi, lunghezza, casting, azione, anelli, peso, potenza, prezzo, new Uri(url));
                    lock (_lock)
                    {
                        _RodsCollection.Add(rod);
                    }
                }
                //clm = new CanneLaMincio(info);
                //info.clearInfo(info);
                codice = "";
                modello = "";
                pezzi = "";
                lunghezza = "";
                casting = "";
                anelli = "";
                peso = "";
                azione = "";

                //specific for GameFish
                marca = "";
            }

            catch (Exception)
            {
                // error handling
#if VERBOSE_MODE
                    MessageBox.Show(ex.Message);
                    throw new Exception("URL" + url);
#endif
            }
            finally
            {
                //if (reader != null)
                //    reader.Close();
                //if (response != null)
                //    response.Close();
            }

        }

        private void GetInfoFalconRodsItalyFast(string html, string url)
        {

            string codice = "-";
            string marca = "FALCON";
            string modello = "-";
            string pezzi = "-";
            string lunghezza = "-";
            string casting = "-";
            string anelli = "-";
            string peso = "-";
            string azione = "-";
            string potenza = "-";
            //double prezzo = 0;
            string prezzo = "-";


            try
            {


                //HtmlAgilityPack...
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.OptionAutoCloseOnEnd = true;
                doc.OptionFixNestedTags = true;
                doc.OptionCheckSyntax = false;
                doc.OptionOutputAsXml = true;
                doc.OptionDefaultStreamEncoding = Encoding.Default;
                doc.LoadHtml(html);
                HtmlAgilityPack.HtmlNode root = doc.DocumentNode;
                HtmlAgilityPack.HtmlNodeCollection htmlNodeColumn = doc.DocumentNode.SelectNodes("//div[@class='tabella_canne']");
                int counter = 0;
                string value;

                foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumn.Descendants("div"))
                {
                    value = RemoveTags(node.InnerText).Replace("&quot;", "\"").Trim();

                    string classValue = node.Attributes["class"].Value;

                    //caratteristica_codice  
                    //caratteristica_nome
                    //caratteristica_lunghezza
                    //caratteristica_azione"
                    //caratteristica_azione
                    //caratteristica_filo
                    //caratteristica_esca

                    switch (classValue)
                    {
                        case "CODICE":
                        case "ITEM #":
                        case "caratteristica_codice":
                            codice = value;
                            //clm.Codice = value;
                            counter += 1;
                            break;
                        case "MODELLO":
                        case "MODEL":
                        case "caratteristica_nome":
                            modello = value;
                            //clm.Modello = value;
                            counter += 1;
                            break;
                        case "PEZZI":
                        case "PIECES":
                            pezzi = value;
                            //clm.Pezzi = value;
                            counter += 1;
                            break;
                        case "LUNGHEZZA":
                        case "caratteristica_lunghezza":
                            lunghezza = value;
                            //clm.Lunghezza = value;
                            counter += 1;
                            break;
                        //case "POTENZA":
                        //case "POWER":
                        //    casting = value;
                        //    //clm.Casting = value;
                        //    counter += 1;
                        //    break;
                        case "ANELLI":
                            anelli = value;
                            //clm.Anelli = value;
                            counter += 1;
                            break;
                        case "PESO":
                        case "LURE WEIGHT":
                            peso = value;
                            //clm.Peso = value;
                            counter += 1;
                            break;
                        case "AZIONE":
                        case "ACTION":
                        case "caratteristica_azione":
                            //distinguo la Action dal Flex
                            //if (value != "")
                            //{
                            //    azione = value;
                            //}
                            if (potenza == "-")
                            {
                                potenza = value.ToUpper();
                            }
                            else
                            {
                                azione = value.ToUpper();
                            }
                            //clm.Azione = value;
                            counter += 1;
                            break;
                        //case "PREZZO":
                        case "POTENZA":
                        case "POWER":
                        case "caratteristica_esca":
                            casting = value;
                            //clm.Casting = value;
                            counter += 1;
                            //break;
                            prezzo = "-";

                            // TODO : UNCOMMENT BELOW CHECK
                            if (CheckValueCasting(casting) && CheckValueLengthStandard(lunghezza) && CheckValueAction(azione) && CheckValuePower(potenza) && CheckValueBrand(marca))
                            {
                                rod = new Rods(codice, marca, modello, pezzi, lunghezza, casting, azione, anelli, peso, potenza, prezzo, new Uri(url));
                                lock (_lock)
                                {
                                    _RodsCollection.Add(rod);
                                }
                            }
                            //clm = new CanneLaMincio(info);
                            //info.clearInfo(info);
                            codice = "-";
                            modello = "-";
                            pezzi = "-";
                            lunghezza = "-";
                            casting = "-";
                            anelli = "-";
                            peso = "-";
                            potenza = "-";
                            azione = "-";
                            counter = 0;
                            break;
                        default:
                            counter += 1;
                            break;
                    }
                    //} if
                }
            }


            catch (Exception)
            {
                // error handling
#if VERBOSE_MODE
                MessageBox.Show(ex.Message);
                throw new Exception("URL" + url);
#endif
            }
            finally
            {
                //if (reader != null)
                //    reader.Close();
                //if (response != null)
                //    response.Close();
            }


        }

        private void GetInfoGloomisFast(string html, string url)
        {
            //string resultHTML = null;
            string marca = "G LOOMIS";
            string codice = "-";
            string modello = "-";
            string pezzi = "-";
            string lunghezza = "-";
            string casting = "-";
            string anelli = "-";
            string peso = "-";
            string azione = "-";
            string potenza = "-";
            string prezzo = "-";
            int columnNum = 0;

            try
            {
                //using (var response = WebRequest.Create(url).GetResponse())
                //{
                //    StreamReader reader = null;
                //    reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                //    resultHTML = reader.ReadToEnd();
                //}

                //HtmlAgilityPack...
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.OptionAutoCloseOnEnd = true;
                doc.OptionFixNestedTags = true;
                doc.OptionCheckSyntax = false;
                doc.OptionOutputAsXml = true;
                doc.OptionDefaultStreamEncoding = Encoding.Default;
                doc.LoadHtml(html);
                HtmlAgilityPack.HtmlNode root = doc.DocumentNode;
                //"headrow" is the only key to find the name of columns 
                HtmlAgilityPack.HtmlNodeCollection htmlNodeColumnNum = doc.DocumentNode.SelectNodes("//tr[@class='headrow']");
                if (htmlNodeColumnNum != null)
                {
                    columnNum = htmlNodeColumnNum.Descendants("td").Count();
                    var columnlist = new string[columnNum];
                    int index = 0;
                    foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumnNum.Descendants("td"))
                    {
                        columnlist[index] = RemoveTags(node.InnerText).ToUpper().Trim();
                        index += 1;
                    }

                    //"odd" or "even" are the only way to find all the rows of table
                    HtmlAgilityPack.HtmlNodeCollection htmlNodeColumn = doc.DocumentNode.SelectNodes("//tr[@class='odd']");
                    int counter = 0;
                    string value;
                    for (int i = 1; i <= 2; i++)
                    {
                        if (i == 2)
                        {
                            htmlNodeColumn = doc.DocumentNode.SelectNodes("//tr[@class='even']");
                            counter = 0;
                        }

                        foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumn.Descendants("td"))
                        {
                            value = RemoveTags(node.InnerText).Replace("&#039;", "'").Replace("&#034;", "\"").Trim();
                            switch (columnlist[counter])
                            {
                                case "CODICE":
                                case "ITEM #":
                                    codice = value;
                                    counter += 1;
                                    break;
                                case "MODELLO":
                                case "MODEL":
                                    modello = value;
                                    counter += 1;
                                    break;
                                case "PEZZI":
                                case "PIECES":
                                    pezzi = value;
                                    counter += 1;
                                    break;
                                case "LUNGHEZZA":
                                case "ROD LENGTH":
                                    lunghezza = value;
                                    counter += 1;
                                    break;
                                case "ANELLI":
                                    anelli = value;
                                    counter += 1;
                                    break;
                                case "PESO":
                                case "LURE WEIGHT":
                                    //valori invertiti
                                    casting = value;
                                    counter += 1;
                                    break;
                                case "AZIONE":
                                case "ACTION":
                                    azione = value.ToUpper();
                                    counter += 1;
                                    break;
                                //case "PREZZO":
                                case "POTENZA":
                                case "POWER":
                                    potenza = value.ToUpper();
                                    counter += 1;
                                    //break;
                                    prezzo = "-";

                                    //fixed value
                                    if (CheckValueCastingLureWeight(casting) && CheckValueLengthStandard(lunghezza) && CheckValueAction(azione) && CheckValuePower(potenza) && CheckValueBrand(marca))
                                    {
                                        rod = new Rods(codice, marca, modello, pezzi, lunghezza, casting, azione, anelli, peso, potenza, prezzo, new Uri(url));
                                        lock (_lock)
                                        {
                                            _RodsCollection.Add(rod);
                                        }
                                    }
                                    //clm = new CanneLaMincio(info);
                                    //info.clearInfo(info);
                                    codice = "-";
                                    modello = "-";
                                    pezzi = "-";
                                    lunghezza = "-";
                                    casting = "-";
                                    anelli = "-";
                                    peso = "-";
                                    azione = "-";
                                    counter = 0;
                                    break;
                                default:
                                    counter += 1;
                                    break;
                            }
                        }
                    }
                }
            }


            catch (Exception ex)
            {
                // error handling
                MessageBox.Show(ex.Message);
            }
            finally
            {
                //if (reader != null)
                //    reader.Close();
                //if (response != null)
                //    response.Close();
            }


        }

        private void GetInfoSuperfishFast(string html, string url)
        {

            string codice = "-";
            string marca = "Lamiglas";
            string modello = "-";
            string pezzi = "-";
            string lunghezza = "-";
            string casting = "-";
            string anelli = "-";
            string peso = "-";
            string azione = "-";
            string potenza = "-";
            //double prezzo = 0;
            string prezzo = "-";
            int columnNum = 0;

            try
            {

                //HtmlAgilityPack...
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.OptionAutoCloseOnEnd = true;
                doc.OptionFixNestedTags = true;
                doc.OptionCheckSyntax = false;
                doc.OptionOutputAsXml = true;
                doc.OptionDefaultStreamEncoding = Encoding.Default;
                doc.LoadHtml(html);
                HtmlAgilityPack.HtmlNode root = doc.DocumentNode;

                HtmlAgilityPack.HtmlNode htmlNodeColumnNum = doc.DocumentNode.SelectSingleNode("//tr[@class='tr_int_canne']");
                if (htmlNodeColumnNum != null)
                {
                    columnNum = htmlNodeColumnNum.Descendants("td").Count();
                    //var columnlist = new string[columnNum];
                    var columnlist = new string[columnNum];
                    int index = 0;
                    foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumnNum.Descendants("td"))
                    {
                        columnlist[index] = RemoveTags(node.InnerText).ToUpper().Trim();
                        index += 1;
                    }

                    var prices = new string[columnNum];
                    index = 0;
                    foreach (HtmlAgilityPack.HtmlNode node in doc.DocumentNode.SelectNodes("//td[@class='td_price']"))
                    {
                        prices[index] = RemoveTags(node.InnerText).Replace("&", "").Replace(";", "").Trim();
                        index += 1;
                    }

                    string value;

                    //counter = 0;
                    value = "";

                    int counter = 0;



                    XmlDocument xmlSiblingDoc = new System.Xml.XmlDocument();
                    XmlNode rootNode = xmlSiblingDoc.CreateElement("SIBLING_NODES");
                    xmlSiblingDoc.AppendChild(rootNode);

                    int i = 0;
                    foreach (var node in doc.DocumentNode.SelectNodes("//tr[@class='tr_int_canne']"))
                    {
                        i += 1;
                        XmlNode siblingNode = xmlSiblingDoc.CreateElement("SIBLING");
                        XmlAttribute siblingAttribute = xmlSiblingDoc.CreateAttribute("INDEX");
                        siblingAttribute.Value = i.ToString();
                        siblingNode.Attributes.Append(siblingAttribute);
                        siblingNode.InnerText = node.NextSibling.NextSibling.OuterHtml;
                        rootNode.AppendChild(siblingNode);
                    }

                    XmlNodeList siblingNodes = xmlSiblingDoc.SelectNodes(".//SIBLING");

                    index = 0;
                    foreach (XmlNode siblingNode in siblingNodes)
                    {
                        XmlDocument xmlInsideSibling = new XmlDocument();
                        xmlInsideSibling.LoadXml(siblingNode.InnerText);
                        XmlNodeList siblingNodeList = xmlInsideSibling.SelectNodes("//td");

                        foreach (XmlNode item in siblingNodeList)
                        {

                            value = RemoveTags(item.InnerText).Trim();
                            if (value == "")
                            {
                                value = "-";
                            }
                            //<td nowrap>Modello</td>
                            //<td nowrap>Tipo</td>
                            //<td nowrap>Lungh.</td>
                            //<td nowrap>N.pezzi</td>
                            //<td nowrap>Peso</td>
                            //<td nowrap>Lure W.</td>
                            //<td nowrap>Line W.</td>
                            //<td nowrap>Manico</td>
                            //<td nowrap>Azione</td>
                            //<td nowrap>Potenza</td>

                            switch (columnlist[counter])
                            {
                                case "CODICE":
                                    codice = value;
                                    //clm.Codice = value;
                                    counter += 1;
                                    break;
                                case "MODELLO":
                                    modello = value.Replace(marca, "").Trim();
                                    //clm.Modello = value;
                                    counter += 1;
                                    break;
                                case "N.PEZZI":
                                    pezzi = value;
                                    //clm.Pezzi = value;
                                    counter += 1;
                                    break;
                                case "LUNGH.":
                                    lunghezza = value;
                                    //clm.Lunghezza = value;
                                    counter += 1;
                                    break;
                                case "ANELLI":
                                    anelli = value;
                                    //clm.Anelli = value;
                                    counter += 1;
                                    break;
                                case "PESO":
                                    //valori invertiti
                                    //casting = value;
                                    peso = value;
                                    //clm.Peso = value;
                                    counter += 1;
                                    break;
                                case "LURE W.":
                                    casting = value;
                                    counter += 1;
                                    break;
                                case "AZIONE":
                                    //case "ACTION":
                                    azione = value.ToUpper();
                                    //clm.Azione = value;
                                    counter += 1;
                                    break;

                                case "POTENZA":
                                    potenza = value.ToUpper();

                                    if (CheckValueCasting(casting) && CheckValueLengthStandard(lunghezza) && CheckValueAction(azione) && CheckValuePower(potenza) && CheckValueBrand(marca))
                                    {
                                        prezzo = prices[index];
                                        index += 1;
                                        rod = new Rods(codice, marca.ToUpper(), modello, pezzi, lunghezza, casting, azione, anelli, peso, potenza, prezzo, new Uri(url));
                                        lock (_lock)
                                        {
                                            _RodsCollection.Add(rod);
                                        }
                                    }
                                    //clm = new CanneLaMincio(info);
                                    //info.clearInfo(info);
                                    codice = "-";
                                    modello = "-";
                                    pezzi = "-";
                                    lunghezza = "-";
                                    casting = "-";
                                    anelli = "-";
                                    peso = "-";
                                    azione = "-";
                                    counter = 0;
                                    break;
                                default:
                                    counter += 1;
                                    break;
                            }

                            if (counter == 0)
                                break;
                        }
                    }
                    //}//for
                }
            }


            catch (Exception)
            {
                // error handling
#if VERBOSE_MODE
                MessageBox.Show(ex.Message);
                throw new Exception("URL" + url);
#endif
            }
            finally
            {
                //if (reader != null)
                //    reader.Close();
                //if (response != null)
                //    response.Close();
            }

        }

        private void GetInfoFisherLandiaFast(string html, string url)
        {
            string codice = "-";
            string marca = "SHIMANO";
            string modello = "-";
            string pezzi = "-";
            string lunghezza = "-";
            string casting = "-";
            string anelli = "-";
            string peso = "-";
            string azione = "-";
            string potenza = "-";
            //double prezzo = 0;
            string prezzo = "-";
            int columnNum = 0;
            string tabPath;

            try
            {

                //HtmlAgilityPack...
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.OptionAutoCloseOnEnd = true;
                doc.OptionFixNestedTags = true;
                doc.OptionCheckSyntax = false;
                doc.OptionOutputAsXml = true;
                doc.OptionDefaultStreamEncoding = Encoding.Default;
                doc.LoadHtml(html);
                HtmlAgilityPack.HtmlNode root = doc.DocumentNode;

                HtmlAgilityPack.HtmlNode htmlNodeModelName = doc.DocumentNode.SelectSingleNode("//td[@class='tabpercorso']");
                if (htmlNodeModelName != null)
                {
                    tabPath = htmlNodeModelName.InnerText.Trim().ToUpper();
                    string[] modelli = tabPath.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                    modello = modelli[modelli.Length - 1];
                    modello = RemoveTags(modello).ToUpper().Trim();
                    modello = modello.Replace("CANNA SHIMANO", "");
                }

                //"protit" is the only key to find the name of columns 
                HtmlAgilityPack.HtmlNodeCollection htmlNodeColumnNum = doc.DocumentNode.SelectNodes("//td[@class='protit']");
                if (htmlNodeColumnNum != null)
                {
                    columnNum = htmlNodeColumnNum.Count();
                    var columnlist = new string[columnNum];
                    int index = 0;
                    foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumnNum)
                    {
                        columnlist[index] = RemoveTags(node.InnerText).ToUpper().Trim();
                        index += 1;
                    }

                    //"procelle" is the only to find all the rows of table
                    HtmlAgilityPack.HtmlNodeCollection htmlNodeColumn = doc.DocumentNode.SelectNodes("//td[@class='procelle']");
                    int counter = 0;
                    string value;

                    foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumn)
                    {
                        value = RemoveTags(node.InnerText).Trim();
                        switch (columnlist[counter])
                        {
                            case "CODICE":
                                codice = value;
                                //clm.Codice = value;
                                counter += 1;
                                break;
                            //case "MODELLO":
                            //    modello = value;
                            //    //clm.Modello = value;
                            //    counter += 1;
                            //    break;
                            case "NUMERO ELEMENTI (MM/M)":
                                pezzi = value;
                                //clm.Pezzi = value;
                                counter += 1;
                                break;
                            case "LUNGHEZZA (M)":
                                lunghezza = value.Replace(".", "") + " cm";
                                //clm.Lunghezza = value;
                                counter += 1;
                                break;
                            case "POTENZA (G)":
                                //it's the LineWeight not the LureWeigth, commented out!
                                casting = value;
                                //clm.Casting = value;
                                counter += 1;
                                break;
                            case "NUMERO DEGLI ANELLI":
                                anelli = value;
                                //clm.Anelli = value;
                                counter += 1;
                                break;
                            case "PESO (G)":
                                peso = value;
                                if (peso != "")
                                {
                                    peso = peso + "g";
                                }
                                else
                                {
                                    peso = "";
                                }
                                //clm.Peso = value;
                                counter += 1;
                                break;
                            //case "AZIONE":
                            //    azione = value;
                            //    //clm.Azione = value;
                            //    counter += 1;
                            //    break;
                            case "PREZZO (EURO)":
                                //value = value.Replace("Euro", "").Replace(".", ",");
                                //prezzo = Convert.ToDouble(DeleteRebateFromPrice(value));
                                prezzo = value + " euro";
                                //clm.Prezzo = prezzo;
                                //Create a new instance of CanneLaMincio
                                //clm = new CanneLaMincio(info);
                                counter += 1;
                                break;
                            case "AGGIUNGI":
                                //COMMENT FOR SPEED TEST  ONLY
                                if (CheckValueCasting(casting) && CheckValueLength(lunghezza) && CheckValueAction(azione) && CheckValuePower(potenza) && CheckValueBrand(marca))
                                {
                                    rod = new Rods(codice, marca, modello, pezzi, lunghezza, casting, azione, anelli, peso, potenza, prezzo, new Uri(url));
                                    lock (_lock)
                                    {
                                        _RodsCollection.Add(rod);
                                    }
                                }
                                //clm = new CanneLaMincio(info);
                                //info.clearInfo(info);
                                codice = "-";
                                //modello = "-";
                                pezzi = "-";
                                lunghezza = "-";
                                casting = "-";
                                anelli = "-";
                                peso = "-";
                                azione = "-";
                                potenza = "-";
                                counter = 0;
                                break;
                            default:
                                counter += 1;
                                break;
                        }
                    }
                }//if

            }//try
            catch (Exception)
            {
                // error handling
#if VERBOSE_MODE
                MessageBox.Show(ex.Message);
                throw new Exception("URL" + url);
#endif
            }

        }

        private void GetInfoBasStore()
        {
            #region old_code
            ////BlurEffect blur = new BlurEffect();
            //////blur.Radius = 5;
            //////Application.Current.MainWindow.Effect = blur;

            ////var blur = new BlurEffect();
            ////var current = this.Background;
            ////blur.Radius = 5;
            ////this.Background = new SolidColorBrush(Colors.DarkGray);
            ////this.Effect = blur;

            ////string url = "http://www.bassstoreitaly.com/canne-spinning_1455710.html";
            ////string resultHTML;
            ////// <table class="fckTable"

            ////using (var response = WebRequest.Create(url).GetResponse())
            ////{
            ////    //WebResponse response = null;
            ////    StreamReader reader = null;
            ////    //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            ////    //request.Method = "GET";
            ////    //response = request.GetResponse();
            ////    reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            ////    resultHTML = reader.ReadToEnd();
            ////}

            ////HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            ////doc.OptionAutoCloseOnEnd = true;
            ////doc.OptionFixNestedTags = true;
            ////doc.OptionCheckSyntax = false;
            ////doc.OptionOutputAsXml = true;
            ////doc.OptionDefaultStreamEncoding = Encoding.Default;
            ////doc.LoadHtml(resultHTML);
            ////HtmlAgilityPack.HtmlNode root = doc.DocumentNode;
            //////"fckTable" is the only key to find the name of columns 
            ////HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes("//table[@class='fckTable']");
            ////HtmlNodeCollection nodes;
            ////StringBuilder sb = new StringBuilder();
            ////string[] str;
            ////var strList = new List<string>();
            ////int i = 0;
            //////foreach (var node in nodeCollection)
            //////{
            //////i+=1;
            //////strList.Add(RemoveTags(node.InnerHtml).ToUpper().Trim());
            ////foreach (var item in nodeCollection)
            ////{
            ////    //IEnumerable<HtmlNode> a = item.Descendants();
            ////    //IEnumerable<HtmlNode> b = a.Where(p => p.OriginalName == "th");
            ////    //List<HtmlNode> allElementList = b.ToList<HtmlNode>();
            ////    //var result = allElementList.Select(c => c.InnerText);

            ////    //strList.Add(item.OuterHtml.Trim().Replace("\r", "").Replace("\n", "").Replace("\t", "").ToUpper().Replace("&NBSP;", "").Replace("&QUOT;", "").Replace("&AMP;", "").Replace("NBSP;", ""));
            ////    //strList.Add("************************************************");
            ////    nodes = item.SelectNodes("descendant::td");
            ////    if (nodes != null)
            ////    {
            ////        foreach (var node in nodes)
            ////        {
            ////            strList.Add(node.OuterHtml.Trim().Replace("\r", "").Replace("\n", "").Replace("\t", "").ToUpper().Replace("&NBSP;", "").Replace("&QUOT;", "").Replace("&AMP;", "").Replace("NBSP;", ""));
            ////            strList.Add("************************************************");
            ////        }
            ////        strList.Add("--------------------------------------------------------");
            ////    }
            ////}

            ////strList.Add("************************************************");
            //////sb.Append(RemoveTags(node.InnerText).ToUpper().Trim());
            //////str[i] = RemoveTags(node.InnerText).ToUpper().Trim();
            //////MessageBox.Show(string.Format("value: {0}",node.InnerHtml));
            //////MessageBox.Show(string.Format("value trim: {0}",RemoveTags(node.InnerText).ToUpper().Trim()));
            //////}
            ////File.WriteAllText(@"C:\Users\salvatore\Documents\TMP\BassStoreItaly.txt", doc.DocumentNode.OuterHtml);
            ////File.WriteAllLines(@"C:\Users\salvatore\Documents\TMP\BassStoreItaly_Array.txt", strList);
            ////MessageBox.Show("File created!");
            ////this.Effect = null;
            ////this.Background = current;
            #endregion old_code
        }

        private void ClearActionAndPower()
        {
            _actionFast = false;
            _actionModFast = false;
            _actionExtraFast = false;
            _actionModerate = false;

            _powerMedium = false;
            _powerMediumHeavy = false;
            _powerHeavy = false;
            _powerModHeavy = false;
            _powerExtraHeavy = false;
        }

        private void GetInfoLaMincio()
        {

            //foreach (string urlList in _stringList)
            //Use of parallel task library (PTL) with a state variable to break out of foreach iterations
            Parallel.ForEach(_stringListLaMincio, (urlList, state) =>
            {
                string resultHTML = null;

                ///////////////////////////////
                string url;
                string staticUrl = "http://www.lamincio.com/nqcontent.cfm?a_id=";
                //WebResponse response = null;
                //StreamReader reader = null;
                string codice = "-";
                string marca = "-";
                string modello = "-";
                string pezzi = "-";
                string lunghezza = "-";
                string casting = "-";
                string anelli = "-";
                string peso = "-";
                string azione = "-";
                string potenza = "-";
                //double prezzo = 0;
                string prezzo = "-";
                int columnNum = 0;
                ///////////////////////////////
                url = staticUrl + urlList;
                try
                {
                    using (var response = WebRequest.Create(url).GetResponse())
                    {
                        StreamReader reader = null;
                        reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        resultHTML = reader.ReadToEnd();
                    }

                    //HtmlAgilityPack...
                    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                    doc.OptionAutoCloseOnEnd = true;
                    doc.OptionFixNestedTags = true;
                    doc.OptionCheckSyntax = false;
                    doc.OptionOutputAsXml = true;
                    doc.OptionDefaultStreamEncoding = Encoding.Default;
                    doc.LoadHtml(resultHTML);
                    HtmlAgilityPack.HtmlNode root = doc.DocumentNode;
                    //"titletext" is the only key to find the name of columns 
                    HtmlAgilityPack.HtmlNodeCollection htmlNodeColumnNum = doc.DocumentNode.SelectNodes("//td[@class='titletext']");
                    HtmlAgilityPack.HtmlNode htmlNodeBrand = doc.DocumentNode.SelectSingleNode("//td[@class='bricktitle']");

                    if (htmlNodeBrand != null)
                    {
                        marca = htmlNodeBrand.InnerText.Trim().ToUpper();
                    }

                    if (htmlNodeColumnNum != null)
                    {
                        columnNum = htmlNodeColumnNum.Count();
                        var columnlist = new string[columnNum];
                        int index = 0;
                        foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumnNum)
                        {
                            columnlist[index] = RemoveTags(node.InnerText).ToUpper().Trim();
                            index += 1;
                        }

                        //"titletext2" is the only to find all the rows of table
                        HtmlAgilityPack.HtmlNodeCollection htmlNodeColumn = doc.DocumentNode.SelectNodes("//td[@class='titletext2']");
                        int counter = 0;
                        string value;

                        foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumn)
                        {
                            value = RemoveTags(node.InnerText);
                            switch (columnlist[counter])
                            {
                                case "CODICE":
                                    codice = value;
                                    //clm.Codice = value;
                                    counter += 1;
                                    break;
                                case "MODELLO":
                                    modello = value;
                                    //clm.Modello = value;
                                    counter += 1;
                                    break;
                                case "PEZZI":
                                    pezzi = value;
                                    //clm.Pezzi = value;
                                    counter += 1;
                                    break;
                                case "LUNGHEZZA":
                                    lunghezza = value;
                                    //clm.Lunghezza = value;
                                    counter += 1;
                                    break;
                                case "POTENZA":
                                    casting = value;
                                    //clm.Casting = value;
                                    counter += 1;
                                    break;
                                case "ANELLI":
                                    anelli = value;
                                    //clm.Anelli = value;
                                    counter += 1;
                                    break;
                                case "PESO":
                                    peso = value;
                                    //clm.Peso = value;
                                    counter += 1;
                                    break;
                                case "AZIONE":
                                    azione = value;
                                    //clm.Azione = value;
                                    counter += 1;
                                    break;
                                case "PREZZO":
                                    value = value.Replace("Euro", "").Replace(".", ",");
                                    //prezzo = Convert.ToDouble(DeleteRebateFromPrice(value));
                                    prezzo = DeleteRebateFromPrice(value);
                                    prezzo = prezzo + " euro";
                                    //clm.Prezzo = prezzo;
                                    //Create a new instance of CanneLaMincio
                                    //clm = new CanneLaMincio(info);

                                    //COMMENT FOR SPEED TEST  ONLY
                                    if (CheckValueCasting(casting) && CheckValueLength(lunghezza) && CheckValueAction(azione) && CheckValuePower(potenza) && CheckValueBrand(marca))
                                    {
                                        rod = new Rods(codice, marca, modello, pezzi, lunghezza, casting, azione, anelli, peso, potenza, prezzo, new Uri(url));
                                        lock (_lock)
                                        {
                                            _RodsCollection.Add(rod);
                                        }
                                    }
                                    //clm = new CanneLaMincio(info);
                                    //info.clearInfo(info);
                                    codice = "-";
                                    modello = "-";
                                    pezzi = "-";
                                    lunghezza = "-";
                                    casting = "-";
                                    anelli = "-";
                                    peso = "-";
                                    azione = "-";
                                    counter = 0;
                                    break;
                                default:
                                    counter += 1;
                                    break;
                            }
                        }
                    }


                    #region old_code
                    //    //"titletext2" is the only to find all the rows of table
                    //    HtmlAgilityPack.HtmlNodeCollection htmlNodeCols2 = doc.DocumentNode.SelectNodes("//td[@class='titletext2']");
                    //    //StringBuilder sb = new StringBuilder();
                    //    sb.Clear();
                    //    foreach (HtmlAgilityPack.HtmlNode node in htmlNodeCols2)
                    //    {
                    //        sb.Clear();
                    //        sb.Append(RemoveTags(node.InnerText));
                    //        link = new Uri(url);

                    //        switch (counter % columnNum)
                    //        {
                    //            case 0:
                    //                codice = sb.ToString();
                    //                counter += 1;
                    //                break;
                    //            case 1:
                    //                modello = sb.ToString();
                    //                counter += 1;
                    //                break;
                    //            case 2:
                    //                pezzi = sb.ToString();
                    //                counter += 1;
                    //                break;
                    //            case 3:
                    //                lunghezza = sb.ToString();
                    //                counter += 1;
                    //                break;
                    //            case 4:
                    //                casting = sb.ToString();
                    //                counter += 1;
                    //                break;
                    //            case 5:
                    //                anelli = sb.ToString();
                    //                if (anelli.Contains("Euro"))
                    //                {
                    //                    anelli = "-";
                    //                    peso = "-";
                    //                    prezzoTemp = sb.ToString().Replace("Euro", "").Replace(".", ",");

                    //                    prezzo = Convert.ToDouble(prezzoTemp);
                    //                    clm = new CanneLaMincio(codice, modello, pezzi, lunghezza, casting, anelli, azione, peso, prezzo, link);

                    //                    _CanneSpigolaCostaCollection.Add(clm);
                    //                    counter += 1;
                    //                }
                    //                counter += 1;
                    //                break;
                    //            case 6:
                    //                prezzoTemp = sb.ToString();
                    //                peso = "-";
                    //                if (prezzoTemp.Contains("g"))
                    //                {
                    //                    peso = sb.ToString();
                    //                    counter += 1;
                    //                    break;
                    //                }
                    //                prezzoTemp = prezzoTemp.Replace("Euro", "").Replace(".", ",");
                    //                prezzoTemp = DeleteDoublePrice(prezzoTemp);
                    //                prezzo = Convert.ToDouble(prezzoTemp);

                    //                clm = new CanneLaMincio(codice, modello, pezzi, lunghezza, casting, anelli, azione, peso, prezzo, link);
                    //                _CanneSpigolaCostaCollection.Add(clm);
                    //                counter += 2;
                    //                break;
                    //            case 7:
                    //                prezzoTemp = sb.ToString().Replace("Euro", "").Replace(".", ",");
                    //                prezzoTemp = DeleteDoublePrice(prezzoTemp);
                    //                prezzo = Convert.ToDouble(prezzoTemp);

                    //                clm = new CanneLaMincio(codice, modello, pezzi, lunghezza, casting, anelli, azione, peso, prezzo, link);
                    //                _CanneSpigolaCostaCollection.Add(clm);
                    //                counter += 1;

                    //                break;
                    //        }
                    //    }


                    #endregion old_code
                }
                catch (Exception)
                {
                    // error handling
#if VERBOSE_MODE
                    MessageBox.Show(ex.Message);
                    throw new Exception("URL" + url);
#endif
                }
                finally
                {
                    //commented out for test in parallalization
                    //if (reader != null)
                    //    reader.Close();
                    //if (response != null)
                    //    response.Close();
                }

                //this.Dispatcher.BeginInvoke(new Action(() => 
                //    textBlock1.Text="Link " + url + " ended by task " + Task.CurrentId + Environment.NewLine), null);
            }

            ); //lambda expression

        }

        private void GetInfoLaMincioFast(string html, string url)
        {

            string codice = "-";
            string marca = "-";
            string modello = "-";
            string pezzi = "-";
            string lunghezza = "-";
            string casting = "-";
            string anelli = "-";
            string peso = "-";
            string azione = "-";
            string potenza = "-";
            //double prezzo = 0;
            string prezzo = "-";
            int columnNum = 0;
            ///////////////////////////////
            try
            {
                //HtmlAgilityPack...
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.OptionAutoCloseOnEnd = true;
                doc.OptionFixNestedTags = true;
                doc.OptionCheckSyntax = false;
                doc.OptionOutputAsXml = true;
                doc.OptionDefaultStreamEncoding = Encoding.Default;
                doc.LoadHtml(html);
                HtmlAgilityPack.HtmlNode root = doc.DocumentNode;
                //"titletext" is the only key to find the name of columns 
                HtmlAgilityPack.HtmlNodeCollection htmlNodeColumnNum = doc.DocumentNode.SelectNodes("//td[@class='titletext']");
                HtmlAgilityPack.HtmlNode htmlNodeBrand = doc.DocumentNode.SelectSingleNode("//td[@class='bricktitle']");

                if (htmlNodeBrand != null)
                {
                    marca = htmlNodeBrand.InnerText.Trim().ToUpper();
                }

                if (htmlNodeColumnNum != null)
                {
                    columnNum = htmlNodeColumnNum.Count();
                    var columnlist = new string[columnNum];
                    int index = 0;
                    foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumnNum)
                    {
                        columnlist[index] = RemoveTags(node.InnerText).ToUpper().Trim();
                        index += 1;
                    }

                    //"titletext2" is the only to find all the rows of table
                    HtmlAgilityPack.HtmlNodeCollection htmlNodeColumn = doc.DocumentNode.SelectNodes("//td[@class='titletext2']");
                    int counter = 0;
                    string value;

                    foreach (HtmlAgilityPack.HtmlNode node in htmlNodeColumn)
                    {
                        value = RemoveTags(node.InnerText);
                        switch (columnlist[counter])
                        {
                            case "CODICE":
                                codice = value;
                                //clm.Codice = value;
                                counter += 1;
                                break;
                            case "MODELLO":
                                modello = value;
                                //clm.Modello = value;
                                counter += 1;
                                break;
                            case "PEZZI":
                                pezzi = value;
                                //clm.Pezzi = value;
                                counter += 1;
                                break;
                            case "LUNGHEZZA":
                                lunghezza = value;
                                //clm.Lunghezza = value;
                                counter += 1;
                                break;
                            case "POTENZA":
                                casting = value;
                                if (url == "http://www.lamincio.com/nqcontent.cfm?a_id=9786")
                                {
                                    //As the site specifies --> "Nota Bene: la potenza indicata è la classe di filo consigliata dal produttore"
                                    casting = "";
                                }
                                //clm.Casting = value;
                                counter += 1;
                                break;
                            case "ANELLI":
                                anelli = value;
                                //clm.Anelli = value;
                                counter += 1;
                                break;
                            case "PESO":
                                peso = value;
                                //clm.Peso = value;
                                counter += 1;
                                break;
                            case "AZIONE":
                                azione = value;
                                //clm.Azione = value;
                                counter += 1;
                                break;
                            case "PREZZO":
                                value = value.Replace("Euro", "").Replace(".", ",");
                                //prezzo = Convert.ToDouble(DeleteRebateFromPrice(value));
                                prezzo = DeleteRebateFromPrice(value);
                                prezzo = prezzo + " euro";
                                //clm.Prezzo = prezzo;
                                //Create a new instance of CanneLaMincio
                                //clm = new CanneLaMincio(info);

                                //COMMENT FOR SPEED TEST  ONLY
                                if (CheckValueCasting(casting) && CheckValueLength(lunghezza) && CheckValueAction(azione) && CheckValuePower(potenza) && CheckValueBrand(marca))
                                {
                                    rod = new Rods(codice, marca, modello, pezzi, lunghezza, casting, azione, anelli, peso, potenza, prezzo, new Uri(url));
                                    lock (_lock)
                                    {
                                        _RodsCollection.Add(rod);
                                    }
                                }
                                //clm = new CanneLaMincio(info);
                                //info.clearInfo(info);
                                codice = "-";
                                modello = "-";
                                pezzi = "-";
                                lunghezza = "-";
                                casting = "-";
                                anelli = "-";
                                peso = "-";
                                azione = "-";
                                counter = 0;
                                break;
                            default:
                                counter += 1;
                                break;
                        }
                    }
                }


            }
            catch (Exception)
            {
                // error handling
#if VERBOSE_MODE
                MessageBox.Show(ex.Message);
                throw new Exception("URL" + url);
#endif
            }
            finally
            {
            }

        }


        private string DeleteRebateFromPrice(string prezzoDoppio)
        {
            // esempio: "255.00 240.00" --> "240.00"
            int count = prezzoDoppio.Length - prezzoDoppio.Replace(",", "").Length;
            if (count > 1)
            {
                prezzoDoppio = prezzoDoppio.Substring(prezzoDoppio.IndexOf(",") + 3).Trim();
            }
            return prezzoDoppio;
        }

        #endregion

        #region check values

        private bool CheckValueAction(string azione)
        {

            //MessageBox.Show("azioni: FAST" + _actionFast.ToString() + Environment.NewLine +
            //                "EXTRAFAST:" + _actionExtraFast.ToString() + Environment.NewLine + 
            //                "MODFAST" + _actionModFast.ToString() + Environment.NewLine + 
            //                "MODERATE" + _actionModerate.ToString());

            azione = azione.Trim().ToUpper();

            //info not present
            if ((azione == "") || azione == "-")
            {
                return true;
            }
            //check values not selected
            if ((_actionFast == false) && (_actionExtraFast == false) && (_actionModFast == false) && (_actionModerate == false))
            {
                return true;
            }
            //fast
            if ((_actionFast == true) && (azione == "FAST"))
            {
                return true;
            }
            //extrafast
            if ((_actionExtraFast == true) && ((azione == "X FAST") || (azione == "EX-FAST") || (azione == "EXTRA FAST")))
            {
                return true;
            }
            //mod-fast
            if ((_actionModFast == true) && ((azione == "MOD/FAST") || (azione == "MODERATE/FAST") || (azione == "MODERATE FAST")))
            {
                return true;
            }
            //moderate
            if ((_actionModerate == true) && ((azione == "MOD") || (azione == "MODERATE")))
            {
                return true;
            }
            //fast not checked but present
            if ((_actionFast == false) && (azione == "FAST"))
            {
                return false;
            }
            //extra-fast not checked but present
            if ((_actionExtraFast == false) && ((azione == "X FAST") || (azione == "EX-FAST") || (azione == "EXTRA FAST")))
            {
                return false;
            }
            //mod-fast not checked but present
            if ((_actionModFast == false) && ((azione == "MOD/FAST") || (azione == "MODERATE/FAST") || (azione == "MODERATE FAST")))
            {
                return false;
            }
            //moderate
            if ((_actionModerate == false) && ((azione == "MOD") || (azione == "MODERATE")))
            {
                return false;
            }

            //MessageBox.Show("azione scartata-->" + azione);
            return false;
        }

        private bool CheckValuePower(string potenza)
        {
            potenza = potenza.Trim().ToUpper();

            //info not present
            if (potenza == "" || potenza == "-")
            {
                return true;
            }
            //check values not checked
            if ((_powerMedium == false) && (_powerMediumHeavy == false) && (_powerHeavy == false) && (_powerModHeavy == false) && (_powerExtraHeavy == false))
            {
                return true;
            }
            //medium
            if ((_powerMedium == true) && (potenza == "MEDIUM"))
            {
                return true;
            }
            //med-heavy
            if ((_powerMediumHeavy == true) && ((potenza == "MED-HEAVY") || (potenza == "MEDIUM HEAVY")))
            {
                return true;
            }
            //heavy
            if ((_powerHeavy == true) && (potenza == "HEAVY"))
            {
                return true;
            }
            //mod-heavy
            if ((_powerModHeavy == true) && ((potenza == "MOD-HEAVY") || (potenza == "MOD HEAVY")))
            {
                return true;
            }
            //extra-heavy
            if ((_powerExtraHeavy == true) && ((potenza == "EXTRA-HEAVY") || (potenza == "EXTRA HEAVY")))
            {
                return true;
            }
            //powerMed not checked but present
            if ((_powerMedium == false) && (potenza == "MEDIUM"))
            {
                return false;
            }
            //powerMedHeavy not checked but present
            if ((_powerMediumHeavy == false) && ((potenza == "MED-HEAVY") || (potenza == "MEDIUM HEAVY")))
            {
                return false;
            }
            //powerHeavy not checked but present
            if ((_powerHeavy == false) && (potenza == "HEAVY"))
            {
                return false;
            }
            //powerModHeavy not checked but present
            if ((_powerModHeavy == false) && ((potenza == "MOD-HEAVY") || (potenza == "MOD/HEAVY")))
            {
                return false;
            }
            //powerExtraHeavy not checked but present
            if ((_powerExtraHeavy == false) && ((potenza == "EXTRA-HEAVY") || (potenza == "EXTRA HEAVY")))
            {
                return false;
            }

            //MessageBox.Show("Potenza scartata : " + potenza);
            return false;
        }

        private bool CheckValueBrand(string brand)
        {
            brand = brand.Trim().ToUpper();

            //info not present
            if (brand == "" || brand == "-")
            {
                return true;
            }
            //option not setted
            if ((string.IsNullOrEmpty(_brand)) || (string.IsNullOrEmpty(_brand)))
            {
                return true;
            }
            //check the same value
            if ((brand == _brand) || (brand == _brand.ToUpper()))
            {
                return true;
            }

            return false;
        }

        private bool CheckValueLenghtConstraint(decimal value)
        {
            return ((value >= this._minLengthValue) && (value <= this._maxLengthValue));
        }

        private bool CheckValueLength(string lunghezza)
        {

            if (lunghezza == "" || lunghezza == "-")
                return true;

            decimal value = 0;
            try
            {

                //inserire il controllo sulla lunghezza: minore o ugale a 240 cm, oppure 8pollici
                if ((lunghezza.Contains("cm") || (lunghezza.Contains("cn")) || (lunghezza.Contains("c"))) && (!(lunghezza.Contains("'") || lunghezza.Contains("’"))))
                {
                    //standard value : "180cm" or "180c"
                    value = Convert.ToDecimal(lunghezza.Replace("cm", "").Replace("cn", "").Replace("c", ""));
                    return CheckValueLenghtConstraint(value);
                }
                if ((lunghezza.Contains("cm") || (lunghezza.Contains("cn")) || (lunghezza.Contains("c"))) && (lunghezza.Contains("'") || lunghezza.Contains("’")))
                {
                    //special case : "7' 213cm"
                    return CheckValueLengthFeetAndCm(lunghezza);
                    //return Convert.ToDecimal(lunghezza.Replace("cm", "")) < maxLengthCentimeter;
                }
                if ((lunghezza.Contains("'") || lunghezza.Contains("’")) && (!lunghezza.Contains(",")) && (!lunghezza.Contains("/")))
                {
                    int count = lunghezza.Length - lunghezza.Replace("'", "").Length;
                    if (count == 1)
                    {
                        // standard value : "9’"
                        value = Convert.ToDecimal(lunghezza.Replace("'", ",").Replace("’", ",").Replace('"', ' ').Replace("”", "")) * _FOOT;
                        return CheckValueLenghtConstraint(value);
                    }
                    if (count == 2)
                    {   // special case : "6'10''
                        value = Convert.ToDecimal(lunghezza.Replace("''", "\"").Replace("”", "\""));
                        return CheckValueLengthFeet(lunghezza.Replace("''", "\"").Replace("”", "\""), '\'');

                        //return Convert.ToDecimal(lunghezza.Replace("''", "\"").Replace("'", ",").Replace("’", ",").Replace('"', ' ').Replace("”", "")) <= this._maxLengthFeet;
                    }

                }
                if ((lunghezza.Contains("'") || lunghezza.Contains("’")) && (!lunghezza.Contains(",")) && (lunghezza.Contains("/")))
                {
                    // special case : "6’2”/186"
                    return CheckValueLengthCm(lunghezza);
                }
                if (lunghezza.Contains("'") && lunghezza.Contains(","))
                {
                    //special case : "6,8'"
                    return CheckValueLengthFeet(lunghezza, '\'');
                }
                if (lunghezza.Contains("’") && lunghezza.Contains(','))
                {
                    // special case : "8,8’"
                    return CheckValueLengthFeet(lunghezza, '’');
                }

            }
            catch (Exception)
            {
                //MessageBox.Show("Errore nella conversione della lunghezza : " + lunghezza + Environment.NewLine + "Dettagli errori: " + e.Message);
                return false;
            }

            return true;
        }

        private bool CheckValueLengthStandard(string lunghezza)
        {
            // value "6'" or "6' 6" "

            if ((lunghezza == "") || (lunghezza == "-"))
            {
                return true;
            }

            bool retValue = true;
            try
            {

                if (lunghezza.Contains("'") && (!lunghezza.Contains("\"")))
                {
                    // standard value : "6'"
                    return CheckValueLengthFeet(lunghezza.Replace("''", "\"").Replace("”", "\""), '\'');
                    //retValue = Convert.ToDecimal(lunghezza.Replace("'", "")) <= this._maxLengthFeet;
                    //return Convert.ToDecimal(lunghezza.Replace("'", "")) <= this._maxLengthFeet;
                }
                else
                {   // case :  "6' 6\""
                    //string[] lengthValue = new string[2];
                    //lengthValue = lunghezza.Trim().Split('\'');

                    //string lengthTmp = lengthValue[0] + "," + lengthValue[1].Replace("\"", " ").Trim();
                    //decimal length = Convert.ToDecimal(lengthTmp);
                    //retValue = length <= this._maxLengthFeet;
                    return CheckValueLengthFeet(lunghezza.Replace("''", "\"").Replace("”", "\"").Replace("\"", " ").Trim(), '\'');
                }

            }

            catch (Exception)
            {
                //MessageBox.Show("Errore nella conversione della lunghezza : " + lunghezza + Environment.NewLine + "Dettagli errori: " + e.Message);
                retValue = false;
            }

            return retValue;
        }

        private bool CheckValueLengthFeetAndCm(string lunghezza)
        {
            //special case : "7' 213cm"
            decimal cm;
            string[] lenghtValue = new string[2];
            lenghtValue = lunghezza.Split(' ');
            if (lenghtValue.Count() == 2)
            {
                if (string.IsNullOrEmpty(lenghtValue[0]))
                {
                    lenghtValue[0] = "0";
                }
                if (string.IsNullOrEmpty(lenghtValue[1]))
                {
                    lenghtValue[1] = "0";
                }
                //feet = Convert.ToDecimal(lenghtValue[0]);
                cm = Convert.ToDecimal(lenghtValue[1].Replace("cm", "").Replace("cn", "").Replace("c", ""));

                //I just check the cm parameter, not also the feet one
                return CheckValueLenghtConstraint(cm);// < this._maxLengthCm;
            }
            cm = Convert.ToDecimal(lunghezza.Replace("cm", "").Replace("cn", "").Replace("c", ""));
            return CheckValueLenghtConstraint(cm);
            //return Convert.ToDecimal(lunghezza.Replace("cm", "").Replace("cn", "").Replace("c", "")) <= this._maxLengthCm;
        }

        private bool CheckValueLengthCm(string lunghezza)
        {
            decimal cm;
            //decimal feet;
            string[] lenghtValue = new string[2];
            lenghtValue = lunghezza.Split('/');
            if (lenghtValue.Count() == 2)
            {
                if (string.IsNullOrEmpty(lenghtValue[0]))
                {
                    lenghtValue[0] = "0";
                }
                if (string.IsNullOrEmpty(lenghtValue[1]))
                {
                    lenghtValue[1] = "0";
                }
                //feet = Convert.ToDecimal(lenghtValue[0]);
                cm = Convert.ToDecimal(lenghtValue[1]);

                //I just check the cm parameter, not also the feet one
                //return cm <= this._maxLengthCm;
                return CheckValueLenghtConstraint(cm);
            }
            return true;
        }

        private bool CheckValueLengthFeet(string lunghezza, char splitterFeet)
        {
            decimal feet;
            decimal inch;
            //char splitterFeetChar = splitterFeet[0];
            string[] lenghtValue = new string[2];

            lenghtValue = lunghezza.Split(splitterFeet);

            if (lenghtValue.Count() == 2)
            {
                if (string.IsNullOrEmpty(lenghtValue[0]))
                {
                    lenghtValue[0] = "0";
                }
                if (string.IsNullOrEmpty(lenghtValue[1]))
                {
                    lenghtValue[1] = "0";
                }
                feet = Convert.ToDecimal(lenghtValue[0]);
                inch = Convert.ToDecimal(lenghtValue[1]);
                return CheckValueLenghtConstraint(feet * _FOOT + inch * _INCH);
                //return (feet <= this._maxLengthFeet);
            }
            if (lenghtValue.Count() == 1)
            {
                if (string.IsNullOrEmpty(lenghtValue[0]))
                {
                    lenghtValue[0] = "0";
                }
                if (string.IsNullOrEmpty(lenghtValue[1]))
                {
                    lenghtValue[1] = "0";
                }
                feet = Convert.ToDecimal(lenghtValue[0]);
                //inch = 0;
                inch = Convert.ToDecimal(lenghtValue[1]);
                return CheckValueLenghtConstraint(feet * _FOOT + inch * _INCH);
                //return (feet <= this._maxLengthFeet);
            }
            return true;
        }

        private bool CheckValueCasting(string value)
        {
            //controllo che il casting sia : A-B --> A minore o uguale a 10, B minore o uguale a 30
            //esempio: "5-25g" oppure "1/8-5/16once" oppure "3/8-2 1/4" oppure "3/8-1once"

            if ((value == "") || (value == "-"))
            {
                return true;
            }

            if (value.Contains("g"))
            {
                return CheckValueCastingGram(value);
            }
            else if (value.Contains("once"))
            {
                return CheckValueCastingOnce(value);
            }
            else if ((value.Contains("oz")) || (value.Contains("Oz")))
            {
                //"1/2-1 1/4oz"
                return CheckValueCastingOz(value);
            }
            else if (value.Contains("/"))
            {
                //"3/8-2 1/4"
                return CheckValueCastingOnce(value);
            }

            return true;
        }

        private bool CheckValueCastingLureWeight(string value)
        {
            //controllo che il casting sia : A-B --> A minore o uguale a 10, B minore o uguale a 30
            //esempio: "1/32 -1/4" opp. "1/4 - 1 " once (per Gloomis)
            //esempio : "1-6" opp. "2-10" once (per Lamiglas)

            if ((value == "") || (value == "-"))
            {
                return true;
            }
            decimal A_1 = 1;
            decimal B_1 = 1;
            decimal A_2 = 1;
            decimal B_2 = 1;
            string[] castingValue = new string[2];
            string[] castingValueOunceA = new string[2];
            string[] castingValueOunceB = new string[2];
            decimal convertedValue;

            try
            {

                castingValue = value.Split('-');
                castingValueOunceA = castingValue[0].Split('/');
                castingValueOunceB = castingValue[1].Split('/');

                //A value
                if (castingValueOunceA.Count() == 2)
                {
                    // standard : "1/32 -1/4"
                    A_1 = Convert.ToDecimal(castingValueOunceA[0]);
                    A_2 = Convert.ToDecimal(castingValueOunceA[1]);
                }
                else if (castingValueOunceA.Count() == 1)
                {   // standard : "1 -1/4"
                    A_1 = Convert.ToDecimal(castingValueOunceA[0]);
                    A_2 = 1;
                }

                //B value
                if (castingValueOunceB.Count() == 2)
                {
                    // standard : "1/32 -1/4"
                    B_1 = Convert.ToDecimal(castingValueOunceB[0]);
                    B_2 = Convert.ToDecimal(castingValueOunceB[1]);
                }
                else if (castingValueOunceB.Count() == 1)
                {
                    // standard : "1/32 -1/4"
                    B_1 = Convert.ToDecimal(castingValueOunceB[0]);
                    B_2 = 1;
                }

                //check value
                convertedValue = (A_1 / A_2) * _OUNCE;
                if (convertedValue < this._minCastingValue)
                {
#if VERBOSE_MODE
                    MessageBox.Show("Valore scartato in quanto supera la specifica in CheckValueCastingLureWeight: " + value + ", convertito: " + convertedValue);
#endif
                    return false;
                }
                convertedValue = (B_1 / B_2) * _OUNCE;
                if (convertedValue > this._maxCastingValue)
                {
#if VERBOSE_MODE
                    MessageBox.Show("Valore scartato in quanto supera la specifica in CheckValueCastingLureWeight: " + value + ", convertito: " + convertedValue);
#endif
                    return false;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Errore nel casting delle once in CheckValueCastingLureWeight!!! Valore: " + value + ". Message: " + e.Message);
            }
            return true;

        }

        private bool CheckValueCastingOnce(string value)
        {
            //esempio: "5-25g" oppure "1/8-5/16once" oppure "3/8-2 1/4" oppure "3/8-1once"
            decimal A_1 = 1;
            decimal B_1 = 1;
            decimal A_2 = 1;
            decimal B_2 = 1;
            decimal B_3 = 1;
            string[] castingValue = new string[2];
            string[] castingValueOunceA = new string[2];
            string[] castingValueOunceB = new string[2];
            string[] castingValueOunceB1 = new string[2];
            decimal convertedValue;

            try
            {
                if (value.Contains("-"))
                {
                    if (!value.Contains(" "))
                    {
                        // standard : "1/8-5/16once"
                        castingValue = value.Replace("once", "").Split('-');
                        castingValueOunceA = castingValue[0].Split('/');
                        castingValueOunceB = castingValue[1].Split('/');
                        if (castingValueOunceA.Count() == 2)
                        {
                            A_1 = Convert.ToDecimal(castingValueOunceA[0]);
                            A_2 = Convert.ToDecimal(castingValueOunceA[1]);
                        }
                        else if (castingValueOunceA.Count() == 1)
                        {
                            A_1 = Convert.ToDecimal(castingValueOunceA[0]);
                            A_2 = 1;
                        }

                        if (castingValueOunceB.Count() == 2)
                        {
                            B_1 = Convert.ToDecimal(castingValueOunceB[0]);
                            B_2 = Convert.ToDecimal(castingValueOunceB[1]);
                        }
                        else if (castingValueOunceB.Count() == 1)
                        {
                            // specific : "3/8-1once"
                            B_1 = Convert.ToDecimal(castingValueOunceB[0]);
                            B_2 = 1;
                        }
                    }
                    else
                    {
                        // specific : "3/8-2 1/4once"
                        // or specific : "3/8 - 1once"
                        int count = value.Replace("once", "").Length - value.Replace("once", "").Replace(" ", "").Length;
                        if (count == 1)
                        {
                            // specific : "3/8-2 1/4once"
                            castingValue = value.Replace("once", "").Split('-'); // "3/8", "2 1/4" 
                            castingValueOunceA = castingValue[0].Split('/'); // "3","8"
                            castingValueOunceB = castingValue[1].Split(' '); // "2","1/4"
                            castingValueOunceB1 = castingValueOunceB[1].Split('/'); // "1","4"
                            A_1 = Convert.ToDecimal(castingValueOunceA[0]); // 3
                            A_2 = Convert.ToDecimal(castingValueOunceA[1]); // 8
                            B_1 = Convert.ToDecimal(castingValueOunceB[0]); // 2
                            B_2 = Convert.ToDecimal(castingValueOunceB1[0]); // 1
                            B_3 = Convert.ToDecimal(castingValueOunceB1[1]); // 4
                            B_1 = B_1 + B_2 / B_3; // 2 + 1/4
                        }
                        if (count == 2)
                        {
                            // specific : "3/8 - 1once"
                            castingValue = value.Replace("once", "").Split('-');
                            castingValueOunceA = castingValue[0].Split('/');
                            castingValueOunceB = castingValue[1].Split('/');
                            A_1 = Convert.ToDecimal(castingValueOunceA[0]);
                            A_2 = Convert.ToDecimal(castingValueOunceA[1]);
                            B_1 = Convert.ToDecimal(castingValueOunceB[0]);
                            //B_2 = Convert.ToDecimal(castingValueOunceB[1]);
                            B_2 = 1;
                        }
                    }

                    convertedValue = (A_1 / A_2) * _OUNCE;
                    if (convertedValue < this._minCastingValue)
                    {
#if VERBOSE_MODE
                        MessageBox.Show("Valore scartato in quanto supera la specificain CheckValueCastingOnce: " + value + ", convertito: " + convertedValue);
#endif
                        return false;
                    }
                    convertedValue = (B_1 / B_2) * _OUNCE;
                    if (convertedValue > this._maxCastingValue)
                    {
#if VERBOSE_MODE
                        MessageBox.Show("Valore scartato in quanto supera la specifica in CheckValueCastingOnce: " + value + ", convertito: " + convertedValue);
#endif
                        return false;
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Errore nel casting delle once in CheckValueCastingOnce!!! Valore: " + value + ". Message: " + e.Message);
            }
            return true;
        }

        private bool CheckValueCastingOz(string value)
        {
            //esempio: "1/2-1 1/4oz"
            decimal A_1 = 1;
            decimal B_1 = 1;
            decimal C_1 = 1;
            decimal A_2 = 1;
            decimal B_2 = 1;
            decimal C_2 = 1;
            decimal C_3 = 1;

            string[] castingValue = new string[2];
            string[] castingValueOunceA = new string[2];
            string[] castingValueOunceB = new string[2];
            string[] castingValueOunceC = new string[2];
            decimal convertedValue;

            try
            {
                if (value.Contains("-"))
                {
                    if (!value.Contains(" "))
                    {
                        // standard : "1/8-5/16oz" no spaces
                        castingValue = value.Replace("oz", "").Split('-');
                        castingValueOunceA = castingValue[0].Split('/');
                        castingValueOunceB = castingValue[1].Split('/');
                        if (castingValueOunceA.Count() == 2)
                        {
                            A_1 = Convert.ToDecimal(castingValueOunceA[0]);
                            A_2 = Convert.ToDecimal(castingValueOunceA[1]);
                        }
                        else if (castingValueOunceA.Count() == 1)
                        {
                            A_1 = Convert.ToDecimal(castingValueOunceA[0]);
                            A_2 = 1;
                        }

                        if (castingValueOunceB.Count() == 2)
                        {
                            B_1 = Convert.ToDecimal(castingValueOunceB[0]);
                            B_2 = Convert.ToDecimal(castingValueOunceB[1]);
                        }
                        else if (castingValueOunceB.Count() == 1)
                        {
                            // specific : "3/8-1once"
                            B_1 = Convert.ToDecimal(castingValueOunceB[0]);
                            B_2 = 1;
                        }
                    }
                    else
                    {
                        // specific : "3/8-2 1/4oz"
                        // or specific : "3/8 - 1oz"
                        int count = value.Replace("oz", "").Length - value.Replace("oz", "").Replace(" ", "").Length;
                        if (count == 1)
                        {
                            // specific : "3/8-2 1/4once"
                            castingValue = value.Replace("oz", "").Split(' ');
                            castingValueOunceA = castingValue[0].Split('-');
                            castingValueOunceB = castingValue[1].Split('/');
                            A_1 = Convert.ToDecimal(castingValueOunceA[1]);
                            A_2 = 1;
                            B_1 = Convert.ToDecimal(castingValueOunceB[0]);
                            B_2 = Convert.ToDecimal(castingValueOunceB[1]);
                        }
                        if (count == 2)
                        {
                            // specific : "3/8 - 1once"
                            castingValue = value.Replace("oz", "").Split('-');
                            castingValueOunceA = castingValue[0].Split('/');
                            castingValueOunceB = castingValue[1].Split('/');

                            count = castingValueOunceB[0].Trim().Length - castingValueOunceB[0].Trim().Replace(" ", "").Length;
                            if (count >= 1)
                            {
                                //"1/2-1 1/4"oz
                                A_1 = Convert.ToDecimal(castingValueOunceA[0]);
                                A_2 = Convert.ToDecimal(castingValueOunceA[1]);

                                castingValueOunceC = castingValueOunceB[0].Trim().Split(' ');
                                C_1 = Convert.ToDecimal(castingValueOunceC[0]);
                                C_2 = Convert.ToDecimal(castingValueOunceC[1]);

                                C_3 = Convert.ToDecimal(castingValueOunceB[1]);

                                B_1 = C_1 + C_2 / C_3;
                                B_2 = 1;
                            }
                            else
                            {
                                A_1 = Convert.ToDecimal(castingValueOunceA[0]);
                                A_2 = Convert.ToDecimal(castingValueOunceA[1]);
                                B_1 = Convert.ToDecimal(castingValueOunceB[0]);
                                //B_2 = Convert.ToDecimal(castingValueOunceB[1]);
                                B_2 = 1;
                            }
                        }
                    }

                    convertedValue = (A_1 / A_2) * _OUNCE;
                    if (convertedValue < this._minCastingValue)
                    {
#if VERBOSE_MODE
                        MessageBox.Show("Valore scartato in quanto supera la specifica in CheckValueCastingOz: " + value + ", convertito: " + convertedValue);
#endif
                        return false;
                    }
                    convertedValue = (B_1 / B_2) * _OUNCE;
                    if (convertedValue > this._maxCastingValue)
                    {
#if VERBOSE_MODE
                        MessageBox.Show("Valore scartato in quanto supera la specifica in CheckValueCastingOz: " + value + ", convertito: " + convertedValue);
#endif
                        return false;
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Errore nel casting delle once in CheckValueCastingOz!!! Valore: " + value + ". Message: " + e.Message);
            }
            return true;
        }

        private bool CheckValueCastingGram(string value)
        {
            //esempio: "5-25g" 

            decimal A;
            decimal B;
            string[] castingValue = new string[2];

            value = value.Replace("g", "");
            if (value.Contains("-"))
            {
                castingValue = value.Replace("g", "").Replace(".", ",").Split('-');
            }
            if (value.Contains("/"))
            {
                castingValue = value.Replace("g", "").Replace(".", ",").Split('/');
            }

            A = Convert.ToDecimal(castingValue[0]);
            B = Convert.ToDecimal(castingValue[1]);

            if (A < this._minCastingValue)
            {
#if VERBOSE_MODE
                MessageBox.Show("Valore scartato in quanto supera la specifica in CheckValueCastingGram A: " + value + ", convertito: " + A.ToString());
#endif
                return false;
            }
            if (B > this._maxCastingValue)
            {
#if VERBOSE_MODE
                MessageBox.Show("Valore scartato in quanto supera la specifica in CheckValueCastingGram B: " + value + ", convertito: " + B.ToString());
#endif
                return false;
            }
            return true;
        }


        #endregion

        #region check installation

        private void ApplicationNotValid()
        {
            MessageError error = new MessageError();
            error.txtInfoMessage.Text = "ERRORE DI INSTALLAZIONE." + Environment.NewLine + Environment.NewLine +
                                        "Verificare di aver installato correttamente il programma." + Environment.NewLine +
                                        "L'applicazione verrà terminata.";
            error.ShowDialog();

        }

        private bool IsInstallationValid()
        {
            bool ret = true;
            RegistryKey hklm = Registry.LocalMachine;
            RegistryKey hkSoftware = hklm.OpenSubKey("Software");
            RegistryKey hkcr = Registry.ClassesRoot;
            try
            {
                RegistryKey hkFishingSearch = hkSoftware.OpenSubKey(_REGISTRY_KEY_NAME);
                if ((hkFishingSearch == null) || (hkFishingSearch.GetValue(_REGISTRY_KEY_VALUE).ToString() != _PRODUCT_ID))
                {
                    //key not found
                    ret = false;
                }

                RegistryKey hkSoftwareFake = hkcr.OpenSubKey("Mmedia.RadioServer.as");
                if ((hkSoftwareFake == null) || (hkSoftwareFake.GetValue("CLSID").ToString() != _PRODUCT_ID_FAKE))
                {
                    //key fake not found
                    ret = false;
                }
            }
            catch (Exception)
            {
                //something went wrong, exit
                ret = false;
            }

            return ret;
        }

        #endregion

        #region save to excel

        private void SaveExcel_Click(object sender, RoutedEventArgs e)
        {

            FileStream file;
            string filename;
            DataTable dt;
            Microsoft.Win32.SaveFileDialog dlg;
            MessageInfo miWarning;

            if (_RodsCollection.Count == 0)
            {
                miWarning = new MessageInfo("Non sono presenti dati da salvare.", this);
                miWarning.ShowDialog();
                return;
            }

            dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.DefaultExt = ".xls";
            dlg.Filter = "File Excel (.xls)|*.xls";
            dlg.Title = _APPLICATION_NAME + " - Salva risultati";
            if (dlg.ShowDialog() == false)
            {
                return;
            }

            filename = dlg.FileName;

            try
            {
                file = new FileStream(filename, FileMode.Create, FileAccess.Write);
            }
            catch (Exception)
            {
                miWarning = new MessageInfo("Errore nella creazione del file Excel." +
                                                    Environment.NewLine +
                                                    "Verificare che il file non sia già aperto o di avere i diritti necessari nella directory scelta.", this);
                miWarning.ShowDialog();
                return;
            }

            dt = new DataTable();
            dt.Columns.Add("CODICE", typeof(string));
            dt.Columns.Add("MARCA", typeof(string));
            dt.Columns.Add("MODELLO", typeof(string));
            dt.Columns.Add("PEZZI", typeof(string));
            dt.Columns.Add("LUNGHEZZA", typeof(string));
            dt.Columns.Add("CASTING", typeof(string));
            dt.Columns.Add("ANELLI", typeof(string));
            dt.Columns.Add("AZIONE", typeof(string));
            dt.Columns.Add("PESO", typeof(string));
            dt.Columns.Add("POTENZA", typeof(string));
            dt.Columns.Add("PREZZO", typeof(string));
            dt.Columns.Add("LINK", typeof(Uri));

            foreach (var i in _RodsCollection)
            {
                dt.Rows.Add(i.Codice, i.Marca, i.Modello, i.Pezzi, i.Lunghezza, i.Casting, i.Anelli, i.Azione, i.Peso, i.Potenza, i.Prezzo, i.Link);

            }

            HSSFWorkbook hssfWorkbook = new HSSFWorkbook();

            HSSFSheet sheet1 = (HSSFSheet)hssfWorkbook.CreateSheet("Canne da spigola dalla costa");
            HSSFRow row1 = (HSSFRow)sheet1.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                HSSFCell cell = (HSSFCell)row1.CreateCell(i);
                string columnName = dt.Columns[i].ToString();
                cell.SetCellValue(columnName);
            }

            //loops through data
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                HSSFRow row = (HSSFRow)sheet1.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    HSSFCell cell = (HSSFCell)row.CreateCell(j);
                    String columnName = dt.Columns[j].ToString();
                    cell.SetCellValue(dt.Rows[i][columnName].ToString());
                }
            }

            hssfWorkbook.Write(file);
            file.Close();

            miWarning = new MessageInfo("File Excel creato con successo.", this);
            //miWarning.Owner = this;
            miWarning.ShowDialog();

#if DEBUG
            StringBuilder sbCatalog = new StringBuilder();
            StringBuilder sbOnlineShop = new StringBuilder();
            string appendix;
            long numItems = 1;
            string internalProductCode;
            appendix = "SPINN";
            //switch (_SEARCH_OPTION)
            //{
            //    case searchOption.CANNE_SPIGOLA_COSTA:
            //        appendix = "A";
            //        break;
            //    case searchOption.CANNE_SERRA_COSTA:
            //        appendix = "B";
            //        break;
            //    case searchOption.CANNE_BARCA:
            //        appendix = "C";
            //        break;
            //    default:
            //        appendix = "X";
            //        break;
            //}

            foreach (var i in _RodsCollection)
            {
                internalProductCode = appendix + numItems.ToString().PadLeft(8, '0');
                sbCatalog.Append(@"
                INSERT INTO [dbo].[Catalogo]
                   ([Online]
                   ,[CodiceProdottoInterno]
                   ,[TecnicaPesca]
                   ,[Ambiente]
                   ,[TipologiaProdotto]
                   ,[Marca]
                   ,[Codice]
                   ,[Modello]
                   ,[Descrizione]
                   ,[Lunghezza]
                   ,[Casting]
                   ,[NumPezzi]
                   ,[Potenza]
                   ,[Azione]
                   ,[Peso]
                   ,[Colore]
                   ,[TipoFrizione]
                   ,[MisuraBobina]
                   ,[FamigliaArtificiale])
             VALUES
                   ('1'
                   ,'" + internalProductCode + @"'
                   ,'spinning'
                   ,'mare'
                   ,'canna'
                   ,'" + i.Marca.Replace("'", "''") + @"'
                   ,'" + i.Codice.Replace("'", "''") + @"'
                   ,'" + i.Modello.Replace("'", "''") + @"'
                   ,NULL
                   ,'" + i.Lunghezza.Replace("'", "''") + @"'
                   ,'" + i.Casting.Replace("'", "''") + @"'
                   ,'" + i.Pezzi.Replace("'", "''") + @"'
                   ,'" + i.Potenza.Replace("'", "''") + @"'
                   ,'" + i.Azione.Replace("'", "''") + @"'
                   ,'" + i.Peso.Replace("'", "''") + @"'
                   ,NULL
                   ,NULL
                   ,NULL
                   ,NULL)" + Environment.NewLine);

                sbOnlineShop.Append(@"
                INSERT INTO [dbo].[NegoziOnline]
                   ([CodiceProdottoInterno]
                   ,[NomeNegozio]
                   ,[Mail]
                   ,[Telefono]
                   ,[Indirizzo]
                   ,[SitoWeb]
                   ,[CatalogoTrattato]
                   ,[TipologiaProdotto]
                   ,[TecnicaPesca]
                   ,[NomeProdotto]
                   ,[Disponiblita]
                   ,[LinkProdotto])
                VALUES
                   ('" + internalProductCode + @"'
                   ,'" + GetDomainNameFromUrl(i.Link.ToString()) + @"'
                   ,NULL
                   ,NULL
                   ,NULL
                   ,'" + GetDomainFromUrl(i.Link.ToString()) + @"'
                   ,'" + i.Marca.Replace("'", "''") + @"'
                   ,'canna'
                   ,'spinning'
                   ,'" + i.Marca.Replace("'", "''") + @"'
                   ,NULL
                   ,'" + i.Link.ToString() + "')" + Environment.NewLine);

                numItems += 1;
            }
            using (StreamWriter sw = new StreamWriter(filename + "__CATALOGO__" + getSearchOption().Replace(" ", "_") + ".sql"))
            {
                sw.Write(sbCatalog.ToString());
            }
            using (StreamWriter sw = new StreamWriter(filename + "__NEGOZIONLINE__" + getSearchOption().Replace(" ", "_") + ".sql"))
            {
                sw.Write(sbOnlineShop.ToString());
            }

#endif
            return;

        }

        #endregion

    }

    #region class for expander

    public class Converter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //we're using OneWayToSource, so this will never be used.
            return DependencyProperty.UnsetValue;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            // we want to convert the single 'IsChecked' value from the ToggleButton into 
            // 3 'IsExpanded' values
            var allValues = new object[targetTypes.Length];
            for (int i = 0; i < allValues.Length; i++)
            {
                allValues[i] = value;
            }

            return allValues;
        }
    }

    public class ExpanderToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (value == parameter);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (System.Convert.ToBoolean(value)) return parameter;
            return null;
        }
    }

    public class ExpanderListViewModel
    {
        public Object SelectedExpander { get; set; }
    }

    #endregion
}
